我對類變量很困惑。我正在查看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.
請停止以粗體大寫字母輸入。 **它真的很討厭**。 –
對不起。我注意到,當代碼沒有正確顯示時,人們會感到惱火。我想確保它不是關於代碼,而是關於這個概念。 – user2522055