Using a private variable in a inherited class - Java

前端 未结 3 1482
暖寄归人
暖寄归人 2020-12-03 06:07

Need to have more understanding about the private variables and inheritance. Earlier my understanding was if there is field in a class and when I\'m inheriting the class, th

3条回答
  •  不思量自难忘°
    2020-12-03 06:23

    class A {
      private int a;
      public A(int a) { this.a = a; }
      public int getA() {return a;}
    }
    
    class B extends A {
      public B(int b) { super(b); }
      public int getB() {return getA();}
    }
    
    int result = new B(10).getA();
    

    result will be 10. Private field a in class A is kind of inherited to B but B can't access it directly. Only by using the public/default/protected accessor methods defined in class A. B is A so it always has all the same fields that are in A and possible some new fields defined in class B.

提交回复
热议问题