java - 为什么重写的方法不表现出多态行为?

标签 java inheritance polymorphism

<分区>

我知道Variables doesn't exhibit polymorphic behavior并且仅限于方法。但是下面的代码在返回对象类型时有点困惑。

它正在调用子方法(这是正确的),这意味着它正在返回子对象。那么为什么不打印子变量的值呢?

class Parent {

    int var = 11;

    public Parent getInstance() {
        System.out.println("In Parent ...");
        return new Parent();
    }
}

class Child extends Parent {

    int var = 22;

    public Child getInstance() {
        System.out.println("In Child ...");
        return new Child();
    }
}


public class VariableHiding {

    public static void main(String[] args) {
        Parent p = new Child();
        System.out.println(p.getInstance().var);  // something's fishy?
    }
}


// Output : In Child ...  11

PS:它不是this one 的副本(里面讲的是变量不参与多态,但是这里说的返回的是child obj的对象,obj持有的是parent的var,而不是自己的)

最佳答案

运行时多态性 无法为变量实现。因此 Parent 类和 Child 类 都有一个公共(public)变量 var

Parent p = new Child();

在这个p中,被class Child引用(属于Parent类的类型)。所以它总是引用父类(super class)变量。

关于java - 为什么重写的方法不表现出多态行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47378581/

相关文章:

java - 为什么我可以用公共(public)方法覆盖 protected 方法?

java - Javacc 终端的奇怪错误

java - 在 Java 中创建一个 Action 监听器(?)

java - java中的KeyAdapter输入不起作用

C# : Is Variance (Covariance/Contravariance) another word for Polymorphism?

C++ 概念检查与继承

c++ - "Call to implicitly deleted default constructor of "错误

java - 无法在另一个 Activity 中读取同一个文件

javascript - Angular Controller 继承/覆盖 "superclass"方法

c++ - 继承在 child 中初始化的数组