Reputation: 15847
Could you please explain me this strange behaviour?
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);
}
}
If you run this code, you it will print twice 3
, instead of 0
, and just then, after initialisation of the field wheels
, 3
.
Upvotes: 0
Views: 54
Reputation: 21004
Because when you refer to wheels
without the this
keyword, you refer to the parameter which value is obviously 3.
Change your line to
System.out.println("Before: " + this.wheels);
or change the parameter name.
Upvotes: 1
Reputation:
The code doesn't print the variable you think it prints.
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);
}
}
If you want to print the variable, use this.wheels
instead.
Upvotes: 0
Reputation: 831
The name wheels
references local variable, not the field wheels
. In both cases, local variable holds value 3
.
If you want reference object's field, use this.wheels
.
Upvotes: 0
Reputation: 1406
You are referencing the local variable instead of class variable.
Use this.wheels
to get the class variable before initialization (which will be 0 not 1) and wheels for the local variable which is 3.
Upvotes: 0