Using a private variable in a inherited class - Java

前端 未结 3 1484
暖寄归人
暖寄归人 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:30

    This is what Java tutorial http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html says:

    A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass.

    Nevertheless, see this

    class A {
       private int i;
    }
    
    class B extends A {
    }
    
    B b = new B();
    Field f = A.class.getDeclaredField("i");
    f.setAccessible(true);
    int i = (int)f.get(b);
    

    it works fine and returns value of field i from B instance. That is, B has i.

提交回复
热议问题