我对类变量很困惑。我正在查看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