2013-10-31 128 views
3

我對類變量很困惑。我正在查看Java Doc教程。他們解釋了靜態變量和方法,但我並不瞭解其中的一個概念。他們給了我們一些代碼,並問我們答案會出來。這個類的變量究竟是如何工作的?

注意該代碼並不完全正確。它不運行的程序但要把握靜態變量

概念的代碼是這樣的:

public class IdentifyMyParts { 
    public static int x = 7; 
    public int y = 3; 
} 

從上面什麼是代碼輸出下面的代碼:

IdentifyMyParts a = new IdentifyMyParts(); //Creates an instance of a class 
IdentifyMyParts b = new IdentifyMyParts(); //Creates an instance of a class 

a.y = 5; //Setting the new value of y to 5 on class instance a  
b.y = 6; //Setting the new value of y to 6 on class instance b 
a.x = 1; //Setting the new value of static variable of x to 1 now. 
b.x = 2; //Setting the new value of static variable of x to 2 now. 

System.out.println("a.y = " + a.y); //Prints 5 
System.out.println("b.y = " + b.y); //Prints 6 
System.out.println("a.x = " + a.x); //Prints 1 
System.out.println("b.x = " + b.x); //Prints 2 
System.out.println("IdentifyMyParts.x = " + IdentifyMyParts.x); 

//Prints2 <- This is because the static variable holds the new value of 2 
//which is used by the class and not by the instances. 

我錯過了什麼,因爲它說System.out.println(「ax =」+ ax); //打印1實際打印2.

+8

請停止以粗體大寫字母輸入。 **它真的很討厭**。 –

+0

對不起。我注意到,當代碼沒有正確顯示時,人們會感到惱火。我想確保它不是關於代碼,而是關於這個概念。 – user2522055

回答

8

靜態變量在類的所有實例之間共享。所以a.xb.x實際上指的是同樣的東西:靜態變量x

你基本上執行以下操作:

IdentifyMyParts.x = 1; 
IdentifyMyParts.x = 2; 

所以X結束爲2

編輯: 基於下面的評論,似乎混亂可能是由於//Prints 1 。 //之後的任何內容都是註釋,並且對代碼完全沒有影響。在這種情況下,評論建議ax的System.out將打印1,但它不正確(因爲不常保留的註釋是......)

+0

我明白這一點。我的問題是關於它打印出來的。我在代碼的最後得到了一個錯誤的代碼? – user2522055

+2

我不確定我明白你在問什麼,然後... a.x,b.x和IdentifyMyParts.x將全部打印出2,因爲它們都指向相同的東西。評論'/ /打印1'是一個評論,建議它會打印什麼,當然它不會 - 忽略這一點,相信代碼;) – Ash

+0

哦..我現在明白了,這很有道理。非常感謝。 – user2522055

3

a.xb.x是完全相同的變量,稱爲以不同的名字。當你一個接一個地打印出來,他們 *具有相同的值(最後一個指定的值),所以這兩個打印將是2

順便說一句,我真的不喜歡的設計決定,允許MyClass.staticVar也可以訪問爲myClassInstance.staticVar。好吧。


*)不完全正確;如果併發線程在兩者之間修改它們,它們可以給出不同的值。如果你還不知道線程,請忽略它。