【问题标题】:Why Runtime Poymorphism behavior changes for Class variables [duplicate]为什么类变量的运行时多态行为会发生变化[重复]
【发布时间】:2012-09-12 10:51:57
【问题描述】:

可能重复:
Hiding instance variables of a class

我有以下课程

抽象测试

public abstract class AbstractTest {
 protected int testVar = 10;
}

测试

public class Test extends AbstractTest {
int testVar = 5;

public static void main(String[] args) {
    AbstractTest test = new Test();
    System.out.println(test.testVar);//Prints 10

    Test secondTest = new Test();
    System.out.println(secondTest.testVar);//Prints 5
}
}

为什么上面的程序在第一种情况下打印10,在第二种情况下打印5,尽管它是同一类的对象,即Test()

更新:

I am now confused about how memory is allocated to Object and its variables. As instance variable is getting changed based on Class which is behaviour of Static?

更新:1

Every object will have two variables so question of same memory allocation does not comes in to picture. Thanks.

【问题讨论】:

    标签: java polymorphism


    【解决方案1】:

    这是在JLS 15.11.1中定义的

    [在表达式 Primary.Identifier] 中,仅使用 Primary 表达式的类型,而不是在运行时引用的实际对象的类来确定使用哪个字段。

    【讨论】:

    • 谢谢。这是一个非常清楚的解释。我想现在我清楚地明白为什么要定义私有变量了。
    • 您能否也回答更新后的问题。提前致谢。
    • 我不太明白你的附加问题。
    【解决方案2】:

    变量是根据类的引用来使用的。所以当AbstractTest使用引用时,testVar是从AbstractTest类中使用的。

    【讨论】:

      【解决方案3】:

      一个硬性规定:

      字段用于引用类型,方法用于实际对象。

      testAbstractTest的引用,所以使用基类字段。

      secondTestderive class的引用,所以使用派生类字段。

      【讨论】:

        猜你喜欢
        • 2021-12-18
        • 2018-07-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-14
        • 2018-08-30
        • 2021-05-15
        相关资源
        最近更新 更多