Quiz: Possibly two correct answers


One question asks: What line of Coode is correct when
initializing an Instance of the Object Dog.

One option is Animal spot = new Dog();

I don't want to cherrypick, but since Dog is a Subtyp of Animal it is formally
correct and possible to store it in a Variable of the super class.

It's not relevant at this point of the course, but that mistake should be avoided as soon as possible :stuck_out_tongue:

(I'm german, so please excuse possible spelling / term mixups)


This is the concept of POLYMORPHISM


Yes, @linkev , you are right. Either of these statements would create an instance of the Dog class, and assign it to the variable, spot:

Animal spot = new Dog();

Dog spot = new Dog();

In both cases, the variable, spot, refers to an instance of Dog, as you could prove by calling a method of the Dog class from that variable. For example, if the Animal class and the Dog class each have their own eat method that takes a String as an argument, then the eat method of the Dog class, rather than that of the Animal class, would execute in the following code ...

Animal spot = new Dog();

It is an example of polymorphism, as @rydan says.