请问有人能解释一下为什么会发生这种情况吗:
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()
方法仍然执行子类方法而不是父类方法?