Let's take this simple Java code:
public class Animal {
public void eat() {
System.out.println("Generic Animal Eating Generically");
}
}
public class Horse extends Animal {
public void eat() {
System.out.println("Horse eating hay ");
}
public void eat(String s) {
System.out.println("Horse eating " + s);
}
}
I'm trying to figure out which version of the three eat() methods will run. Now, when I type
Animal a = new Animal();
a.eat();
The output is "Generic Animal Eating Generically", which is completely understandable.
The same thing happens when I type:
Horse h = new Horse();
h.eat();
The output is "Horse eating hay", which is, again, completely logical.
Here's where it gets confusing for me though. When I type:
Animal ah = new Horse();
ah.eat();
I get:
Horse eating hay
I expected the compiler to invoke the eat() method from the Animal class reference, not the Horse object reference.
So my question is, how can I know for sure which method the compiler is going to invoke when I have a generic reference variable
types referring to an object type (like this one: Animal horse = new Horse();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…