Using a private variable in a inherited class - Java

人盡茶涼 提交于 2019-12-17 11:03:54

问题


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, the fields that is not restricted by access(private variables) will be there in the inherited class. But I'm able use the private variables in base class if there is a public g/setter method.

How can I imagine a private variable in a base class.?


回答1:


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.




回答2:


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.




回答3:


private variables / members are not inherited. That's the only answer.

Providing public accessor methods is the way encapsulation works. You make your data private and provide methods to get or set their values, so that the access can be controlled.



来源:https://stackoverflow.com/questions/15549775/using-a-private-variable-in-a-inherited-class-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!