谁能解释一下为什么会这样:
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()
方法执行子类方法,而不是父类(super class)方法,即使我是向上转型,正如所见?
最佳答案
那是因为这就是多态性在 Java 中的工作方式:它总是使用该方法的最派生版本,覆盖其他版本。获取基类版本的唯一方法是在最派生覆盖中使用 super.setType
。
关于java - 在 Java 中向上转换有问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6729039/