在初始化之前打印字段似乎在我初始化它之后打印它
Printing the field before initialising it seems to print it after I initialise it
你能解释一下这种奇怪的行为吗?
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
。
因为当你引用wheels
时不带this
关键字,你引用的参数显然是3.
将您的线路更改为
System.out.println("Before: " + this.wheels);
或更改参数名称。
您引用的是局部变量而不是 class 变量。
使用this.wheels
在初始化之前获取class变量(这将是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
。
你能解释一下这种奇怪的行为吗?
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
。
因为当你引用wheels
时不带this
关键字,你引用的参数显然是3.
将您的线路更改为
System.out.println("Before: " + this.wheels);
或更改参数名称。
您引用的是局部变量而不是 class 变量。
使用this.wheels
在初始化之前获取class变量(这将是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
。