你能解释一下我这种奇怪的行为吗?
public class Car {
private int wheels;
public Car(int wheels) {
System.out.println("Before: " + wheels); // prints 3 before initialisation
this.wheels = wheels;
System.out.println("After: " + wheels); // prints 3
}
public static void main(String[] args) {
Car car = new Car(3);
}
}
如果你运行这段代码,它将3
打印两次,而不是0
,然后,在初始化字段wheels
之后,3
。
因为当您引用没有 this
关键字的wheels
时,您引用的值显然为 3 的参数。
将线路更改为
System.out.println("Before: " + this.wheels);
或更改参数名称。
您引用的是局部变量而不是类变量。
使用 this.wheels
在初始化之前获取类变量(将为 0 而不是 1)和局部变量 3 的轮子。
名称wheels
引用局部变量,而不是字段wheels
。在这两种情况下,局部变量都保存值3
。
如果需要引用对象的字段,请使用 this.wheels
。
代码不会打印您认为它打印的变量。
public class Car {
private int wheels;//<-- what you think it prints
public Car(int wheels) {//<-- what it actually prints
System.out.println("Before: " + wheels); // prints 3 before initialisation
this.wheels = wheels;
System.out.println("After: " + wheels); // prints 3
}
public static void main(String[] args) {
Car car = new Car(3);
}
}
如果要打印变量,请改用this.wheels
。