Sub class variable is not hiding the variable in super class

105 Views Asked by At

I just learned that if there are two variables, one in super class and one in sub class which share the same name the value assigned to the variable in the subclass will hide the value of the variable in super class. I have written a program to check that out, but the out put is clearly showing that any hiding process is not happening or is it really happening? if the sub class hides the variable in super class the value of "A.a" and "B.a" should be 25 right? help me out please.

Note: I am new to this java programming. explain your answer in detail please. thank you

here is the code

public class Super {
  int a;

  Super(int x) {
    a = x;
  }

}

class something extends Super {
  int a;

  something(int x, int y) {
    super(x);
    a = y;
  }
}

class mainclass {

  public static void main(String args[]) {

    Super A = new Super(10);
    something B = new something(10, 25);

    System.out.println("The value of a in super class is" + A.a);
    System.out.println("The value of a in sub class is" + B.a);
  }
}

output is here:

The value of a in super class is10
The value of a in sub class is25
2

There are 2 best solutions below

7
On BEST ANSWER

A.a shouldn't return 25, since the type of A is the super type Super, and there's no hiding. That's why A.a returns 10.

Only in B.a there's hiding of a (since B is of type something which extends Super and hides member a), which is why it returns 25.

0
On

Yes, tha "a" in the subclass hides the "a" in the super class. Thats why you assign the "a" in the sub class in the constructor of something.