I'am a little confused about two examples in the assessment test!
First code example (I changed a little, because I don't wanted to have abstract class, because I wanted to instantiate the Puma class):
This code results in "4". That's clear for me. But if I change "Puma puma = new Puma();" in "Puma puma = new Cougar(); the result is "2". Nothing changes. The reference type "Puma" has nothing to do, which method "hasTailLength()" from Puma or Cougar will be choosen? But this example is clear for me! I wrote it here to compare with the second one, where the reference type is important!
But I have another example, where the reference type counts:
In this programm the object type is called for the argument constructor "new Reindeer(5);" from the class Reindeer?! Is always the constructor from the right side in: Deer deer = new Reindeer(5); called;? When yes, it's clear for me. And then the implicit super() without args constructor from class Deer is called. Thats why the beginning output is: "DeerReindeer". But know I' don't understand why the reference type is important, because the method from Deer is called??! The method from class Reindeer is only called if I change line 9 to: "Reindeer deer = new Reindeer(5);" then only the method hasHorns() from Reindeer class will be called.
What confuse me is, sometimes one use the reference type otherwise the object type? Is there a rule, in which I can clearly choose one or the other??
The getTailLength() method in the Cougar class overrides the method from its superclass Puma. It is the instance type that determines which of the methods is called.
In your second example, the hasHorns() method in the Deer class is declared private and a private method can't be overridden because it is not accessible from the Reindeer class. The latter class redeclares this method, which is considered a new method not related to the method in the superclass. Because the reference type is of type Deer, the method from the Deer class is called. And vice versa.
posted 3 weeks ago
Ok, thank you.
If I change the method
and then call the method, the result is:
Now the method hasHorns() is overridden, and the method from Reindeer Class will be called!