打印出以下代码:
-7
-7
11 44 -54
11
我认为它应该打印出来:
-7
-7
-11 -44 -54
11
代码是:
import static java.lang.System.out;
public class Point {
public static int x = 0;
public int y = 0;
public static int i = 7;
public static void main(String[] args) {
if (true) Point.x = -7;
out.println(x);
out.println(Point.x);
Point foo = new Point(-11,-44,-54);
Point bar = new Point(11,44,54);
out.println(foo.x + " " + foo.i + " " + foo.y);
out.println(Point.x);
}
//constructor
public Point(int x, int i, int y) {
this.y = y;
this.i = i;
this.x = x;
}
}
如果我删除 Point bar = new Point(11,44,54);
输出是:
-7
-7
-11 -44 -54
11
如果这是相关的:要运行这个程序(在 Point.java
中),我(像往常一样)按 Shift+Ctrl+F9 和 Ctrl+F9 和 Shift+F10。我在安装了所有更新的 Win 8.1 64 位上运行带有 JDK 7u76 的 IntelliJ Idea 14.0.3。
最佳答案
因为 x
是 static
:x
只有一个实例是“共享”类 Point 的所有实例
。这就是该值被覆盖的原因。事实上,x
不与任何对象相关联,而是与类本身相关联。请注意,变量 y
不是这种情况,它是一个实例变量。
所以在下面的代码中:
Point foo = new Point(-11,-44,-54);
Point bar = new Point(11,44,54);
x
设置为 -11
,然后设置为 11
。
关于java - 为什么 println() 打印这个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28518144/