有人可以解释一下为什么会发生这种情况吗:
class Apple {
String type;
setType(){
System.out.println("inside apple class");
this.type = "apple";
}
}
class RedApple extends Apple {
String type;
setType() {
System.out.println("inside red-apple class");
this.type = "redapple";
}
}
int main {
RedApple red = new RedApple();
Apple apple = (Apple) red;
apple.setType();
}
但产生的输出是:
"inside red-apple class”
为什么.setType()
方法执行子类方法,而不是超类方法,即使我向上转换,可以看出吗?
这是因为这就是多态性在 Java 中的工作原理:它总是使用该方法的最派生版本,即覆盖其他版本。获取基类版本的唯一方法是使用super.setType
在最衍生的覆盖内。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)