Search code examples
javaoopvariableslocaloverriding

Value of class attribute in Java


I don't understand how exactly it works.

We have two class A and B. Class B extends A. Class A have x attribute, and test method which modify this attribute. Class B have x attribute, and test method which modify this attribute.

public class A {

    int x;

    public void test() {
         this.x = 1;
        System.out.println("A" + getX());
    }
    int getX() {return x;}
}

public class B extends A {

    int x;

    public void test() {
        this.x = 2;
        System.out.println("B" + getX());
    }
    int getX() {return x;}

}

public class Main {

    public static void main(String[] args) {

        A a = new A();
        a.test();
        System.out.println(a.getX());

        System.out.println("point 1");
        a = new B();
        a.test();
        System.out.println(a.x);
       }
}

Output:

 A1
 1
 point 1
 B2
 0

My prediction about last line of output was 2, but is 0. Why is 0?


Solution

  • Let's understand these lines of code:

    a = new B();
    a.test();
    System.out.println(a.x);
    
    • You create a new object of B. It will re-initialize the variable - A.x = 0 and B.x = 0.
    • Then you invoke a.test(), which will call the overridden method test() in class B, which will set B.x to 2 using this.x = 2;. Note at this point, A.x is still 0.
    • Then you access a.x, which will access the field x in class A. The fields are not polymorphic. You don't override fields, but you hide them. The variable x in B hides the variable x in A.