有人可以解释一下为什么会发生这种情况吗:
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()
方法执行子类方法,而不是超类方法,即使我向上转换,正如可以看到的?
这是任何 OOP 语言的基本特征。这就是为什么 C++ 中的所有解构函数都应该是虚拟的——以实现多态性。使适当的方法被调用。 这是一篇很好的文章,可以帮助您了解其工作原理
但是,这里有一个向上转换确实产生影响的示例:
class MyClass {
static void doSomething(Apple apple) { System.out.println("Apple"); }
static void doSomething(RedApple apple) { System.out.println("RedApple"); }
}
...
RedApple apple = new RedApple();
MyClass.doSomething(apple);
MyClass.doSomething((Apple)apple);
输出:
RedApple
Apple
由于我们将其向上转换为 Apple,因此最佳匹配方法是带有 Apple 参数的方法。
method-hiding即静态方法。