2013-10-31 72 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。好吧。


*)不完全正确;如果并发线程在两者之间修改它们,它们可以给出不同的值。如果你还不知道线程,请忽略它。