如果我将子类转换为其超类,并调用在子类中被重写的方法,那么它执行被重写的方法还是原始方法? [英] 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?
本文介绍了如果我将子类转换为其超类,并调用在子类中被重写的方法,那么它执行被重写的方法还是原始方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑:
Dog
是 Animal
的子类,并且 Dog
覆盖 Animal.eat()
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();
}
如果 Animal.eat()
被 Dog.eat()
覆盖,则当从类型为 Animal的标识符调用该方法时将调用该方法
( animals [i]
?)
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]
?)
推荐答案
将调用子类方法.这就是多态的妙处.
The subclass method will be called. That's the beauty of polymorphism.
这篇关于如果我将子类转换为其超类,并调用在子类中被重写的方法,那么它执行被重写的方法还是原始方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文