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
指代 obj1.y
或 t.y
在 method1
?
为什么没有改变 this.y
任何影响 t.y
?
y
是一个全局实例变量。当你调用 obj1.method1(10);
, this
在 method1
指的是 obj1
. 所以... this.y
指代 obj1.y
方法1中。
为什么改变this.y对t.y没有任何影响?
因为 this
指的是 obj1
所以你是在改变 obj1
不 t
.