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