francisco de feudis wrote:In my mind the actual object is of type Reindeer, so I think that conceptually and actually the private hasHorns methods doesn't exists in that object and should never be used, even if the morph of the object is Deer.
For the compiler the actual object doesn't matter at all! The only thing the compiler knows (and cares about) is the type of the reference variable, which is in this case
Deer. And the
Deer class defines a private method
hasHorns(). So that means the
hasHorns() method can only be used within the
Deer class. Luckily the
main() method is defined in the
Deer class as well, so it is valid to access the private
hasHorns() method. If the
main() method was defined in the
Reindeer class, the code would not compile and give a compiler error.
Although the
Reindeer class defines a public
hasHorns() method too, this method is not executed at runtime. Because only inherited methods can be overridden and a
private method is never inherited. If you would remove the
private access modifier or change it to
protected or
public, the output will be different. In
this topic you'll find an excellent explanation (with lots of code snippets) about how changing the access modifier of a method can influence which method is executed (and thus result in a different output). Definitely worth reading!
Here is a
very, very, very important rule: The compiler doesn't execute any code! So every compiler error you get, is because the compiler knows something is wrong without executing any line of code. So the compiler doesn't know and care) about the actual objects, the compiler only knows about the types of the reference variables.
Hope it helps!
Kind regards,
Roel
PS. What is a "morph"?