Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 621
Marcin Tomasik Avatar asked Dec 25 '22 12:12

Marcin Tomasik


2 Answers

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.
like image 71
Rohit Jain Avatar answered Jan 07 '23 00:01

Rohit Jain


If both A and B have a member named x, the one in B will block access to the one inherited from A. Remove the int x; declaration from B, or explicitly use super.x, if you want to reference the one in the parent class.

like image 26
keshlam Avatar answered Jan 06 '23 23:01

keshlam