简体   繁体   中英

Sub class variable is not hiding the variable in super class

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 "Aa" and "Ba" 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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM