[英]If I've cast a subclass as its superclass, and call a method that was overridden in the subclass, does it perform the overridden or original method?
Consider: 考虑:
Dog
is a subclass of Animal
, and Dog
overrides Animal.eat()
Dog
是Animal
的子类, Dog
覆盖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]
?) 如果Animal.eat()
覆盖了Dog.eat()
,那么从Animal
类型的标识符调用方法时会调用哪一个( animals[i]
?)
The subclass method will be called. 将调用子类方法。 That's the beauty of polymorphism . 这就是多态的美。
The subclass will be the only method call, unless the subclass calls the superclass like this: 除非子类像这样调用超类,否则子类将是唯一的方法调用:
class Dog {
public eat() {
super.eat();
}
}
The code 编码
Animal a = new Dog();
a.eat();
will call Dog's eat
method. 会叫狗的eat
。 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: 你有一个Cat定义了一个额外的方法:
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!". 这将打印“Just a a a a cute mouse”,而不是“Grabbed a MOUSE!”。 Why? 为什么? Because polymorphism only works for the object to the left of the dot in a method invocation. 因为多态只适用于方法调用中点左侧的对象。
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! 如果您无法传递作为其超类的子类化对象并且未获得子类方法,那么继承将毫无用处!
/**
* @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");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.