Java 中向上转型的问题?

问题描述 投票:0回答:4

有人可以解释一下为什么会发生这种情况吗:

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 polymorphism upcasting
4个回答
7
投票

那是因为这就是 多态性 在 Java 中的工作原理:它始终使用该方法的最派生版本,该版本覆盖其他版本。

获取基类版本的唯一方法是在最派生的覆盖中使用

super.setType


2
投票

这是任何 OOP 语言的基本特征。这就是为什么 C++ 中的所有解构函数都应该是虚拟的——以实现多态性。使适当的方法被调用。 这是一篇很好的文章,可以帮助您了解其工作原理


1
投票
这是多态性,您已经重写了该方法,因此现在每当您在该对象上调用该方法时,即使它被转换为超类,也会调用最子级的方法。

但是,这里有一个向上转换确实产生影响的示例:

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 参数的方法。


0
投票
这就是 java 的设计工作方式,称为方法的重写行为。如果您想在超类中使用该方法,您可以在父类和子类中使用具有相同签名的

method-hiding即静态方法。

© www.soinside.com 2019 - 2024. All rights reserved.