2012-09-12 26 views
3

可能重複:
Hiding instance variables of a class爲什麼運行Poymorphism行爲類變量的變化

我有以下類

AbstractTest

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.

回答

2

這在JLS 15.11.1

定義[在式Primary.Identifier],只有主表達式的類型,而不是類的實際對象的在運行時的簡稱,是在確定哪些領域中使用的使用。

+0

謝謝。這是一個非常明確的解釋。我想現在我清楚地理解爲什麼要定義變量private。 –

+0

你能否請回答更新的問題。提前致謝。 –

+0

我真的不明白你的額外問題。 – assylias

1

變量是基於類的基準使用。因此,當使用AbstractTest參考testVar是從AbstractTest類使用。

1

一個硬&快速的法則:

中的字段用於引用類型,同時使用的實際對象的方法。

testAbstractTest的參考,因此使用基類字段。

secondTestderive class的參考,所以使用派生類字段。

相關問題