我正在 Java 中处理静态变量和实例变量,我无法理解代码的输出
I am working on static and instance variables in Java, where I couldn't understand the output of the code
package java_course;
public class staticVsInstance {
static int x = 11;
private int y = 33;
public void method1(int x) {
staticVsInstance t = new staticVsInstance();
System.out.println("t.x "+t.x + " " +"t.y "+ t.y + " " +"x "+ x + " "+"y " + y);
this.x = 22;
this.y = 44;
System.out.println("t.x "+t.x + " " +"t.y "+ t.y + " " +"x "+ x + " "+"y " + y);
}
public static void main(String args[]) {
staticVsInstance obj1 = new staticVsInstance();
System.out.println(obj1.y);
obj1.method1(10);
System.out.println(obj1.y);
}
}
输出为
33
t.x 11 t.y 33 x 10 y 33
t.x 22 t.y 33 x 10 y 44
44
this.y
指的是method1
中的obj1.y
还是t.y
?
为什么更改 this.y
对 t.y
没有任何影响?
y
是一个全局实例变量。当你调用 obj1.method1(10);
时,method1
中的 this
指的是 obj1
。所以this.y
参考method1中的obj1.y
。
Why hasn't changing this.y any affect on t.y?
因为 this
指的是 obj1
所以你改变的是 obj1
的实例变量而不是 t
.
package java_course;
public class staticVsInstance {
static int x = 11;
private int y = 33;
public void method1(int x) {
staticVsInstance t = new staticVsInstance();
System.out.println("t.x "+t.x + " " +"t.y "+ t.y + " " +"x "+ x + " "+"y " + y);
this.x = 22;
this.y = 44;
System.out.println("t.x "+t.x + " " +"t.y "+ t.y + " " +"x "+ x + " "+"y " + y);
}
public static void main(String args[]) {
staticVsInstance obj1 = new staticVsInstance();
System.out.println(obj1.y);
obj1.method1(10);
System.out.println(obj1.y);
}
}
输出为
33
t.x 11 t.y 33 x 10 y 33
t.x 22 t.y 33 x 10 y 44
44
this.y
指的是method1
中的obj1.y
还是t.y
?
为什么更改 this.y
对 t.y
没有任何影响?
y
是一个全局实例变量。当你调用 obj1.method1(10);
时,method1
中的 this
指的是 obj1
。所以this.y
参考method1中的obj1.y
。
Why hasn't changing this.y any affect on t.y?
因为 this
指的是 obj1
所以你改变的是 obj1
的实例变量而不是 t
.