0

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.

nbro
  • 15,395
  • 32
  • 113
  • 196

4 Answers4

1

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.

nbro
  • 15,395
  • 32
  • 113
  • 196
Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
0

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.

nbro
  • 15,395
  • 32
  • 113
  • 196
tinker
  • 1,396
  • 11
  • 20
0

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.

nbro
  • 15,395
  • 32
  • 113
  • 196
Ernest Sadykov
  • 831
  • 8
  • 28
0

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.

nbro
  • 15,395
  • 32
  • 113
  • 196