我是Java编程语言的新手.
我熟悉C和C但无法理解下面程序的行为.
public class Test {
static int x = 11;
private int y = 33;
public void method1(int x) {
Test t = new Test();
this.x = 22;
y = 44;
System.out.println("Test.x: " + Test.x);
System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
}
public static void main(String args[]) {
Test t = new Test();
t.method1(5);
}
}
正确的输出:
Test.x: 22
t.x: 22
t.y: 33
y: 44
预期产量:
Test.x: 22
t.x: 22
t.y: 44 // As variable y is modified inside the function.
y: 44
甚至改变y = 44的线;到this.y = 44;没有给出预期的产出.
解决方法:
问题是你没有提到创建的实际对象.您正在从具有新变量的其他实例中获取变量.
Test t = new Test();
this.x = 22;
y = 44;
System.out.println("Test.x: " + Test.x);
System.out.println("t.x: " + t.x);
System.out.println("t.y: " + t.y);
System.out.println("y: " + y);
如果你仔细看第一行Test t = new Test();
你没有在y指定为44的特定实例上调用method1.因此,您可以看到顶级值.
如果重命名实例,将会更清楚.而不是总是.
这就是混淆的原因,而且你在里面调用method1()可能会导致无限循环.
标签:java,static,class-level
来源: https://codeday.me/bug/20190522/1153289.html