The method eat
in Dog
does not override the method eat
in Animal
. This is because the arguments are different (one requires Flesh
, the other requires Food
).
The eat
methods are overloads.
Choosing between overloads takes place at compile time, not runtime. It is not based on the actual class of the object on which the method is invoked, but the compile-time type (how the variable is declared).
animal
has compile-time type Animal
. We know this because the declaration of the variable animal
was Animal animal = ...
. The fact that it is actually a Dog
is irrelevant - it is the version of eat
in Animal
that must be invoked.
On the other hand, the toString
method in Flesh
does override the toString
method in Food
.
When one method overrides another it is the actual class of the object that the method is invoked on that determines which version runs.
In the eat
method of Animal
, even though the argument has compile-time type Food
, if you pass an instance of Flesh
to it, it is the toString
method in Flesh
that will execute.
Therefore you get the message "Animal eats Flesh Food"
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…