问题
Consider:
Dog
is a subclass of Animal
, and Dog
overrides Animal.eat()
Animal[] animals = getAllAnimals();
for (int i = 0; i < animals.length; i++) {
animals[i].eat();
}
If Animal.eat()
is overriden by Dog.eat()
, which one is called when the method is called from an identifier of type Animal
(animals[i]
?)
回答1:
The subclass method will be called. That's the beauty of polymorphism.
回答2:
The subclass will be the only method call, unless the subclass calls the superclass like this:
class Dog {
public eat() {
super.eat();
}
}
回答3:
The code
Animal a = new Dog();
a.eat();
will call Dog's eat
method. But beware! If you had
class Animal {
public void eat(Animal victim) {
System.out.println("Just ate a cute " + victim.getClass().getSimpleName());
}
}
and you have a Cat that defines an additional method:
class Cat extends Animal {
public void eat(Mouse m) { System.out.println("Grabbed a MOUSE!"); }
}
and then you use them:
Animal cat = new Cat();
Animal mouse = new Mouse();
cat.eat(mouse);
This will print "Just ate a cute Mouse", and not "Grabbed a MOUSE!". Why? Because polymorphism only works for the object to the left of the dot in a method invocation.
回答4:
It'll call the version in the subclass.
Inheritance would be pretty useless if you couldn't pass around a subclassed object cast as its superclass and not get the subclassed method!
回答5:
A sscce
/**
* @author fpuga http://conocimientoabierto.es
*
* Inheritance test for http://stackoverflow.com/questions/10722447/
*
*/
public class InheritanceTest {
public static void main(String[] args) {
Animal animals[] = new Animal[2];
animals[0] = new Animal();
animals[1] = new Dog();
for (int i = 0; i < animals.length; i++) {
animals[i].eat();
if (animals[i] instanceof Dog) {
System.out.println("!!Its a dog instance!!");
((Dog) animals[i]).eat();
}
}
}
private static class Animal {
public void eat() {
System.out.println("I'm an animal");
}
}
private static class Dog extends Animal {
@Override
public void eat() {
System.out.println("I'm dog");
}
}
}
来源:https://stackoverflow.com/questions/10722447/if-ive-cast-a-subclass-as-its-superclass-and-call-a-method-that-was-overridden