1、父类Father定义一个private int = 7;的成员变量。public class Father { private int i = 7;}
2、子类Son继承父类Father 。public class Son extends Father {}
3、主程碌食撞搁序new一个Father对象和new一个Son对象。public class MainActivity extends 帆歌达缒AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Father father = new Father(); Son son= new Son(); }}
4、使用Debug模式观察实例化结果。可以看到Son里维护了一个i变量。然而,这并不能证明子类继承了父类私有属性。
5、因此子类直接操作是不可以的,既然是父类的私有成员,那么就可以通过父类方法操作,下面在父类定义了get,set方法。public class Father { private int i = 7; public int getI() { return i; } public void setI(int i) { this.i = i; }}
6、在主程序中通过get()拿到这个成员变量的值,并打印,如下图。
7、最后附上java官方文档的解释:Private Members in a SuperclassA subclass does not 足毂忍珩inherit theprivatemembers 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.A nested class has access to all the private members of its enclosing class—both fields and methods. Therefore, a public or protected nested class inherited by a subclass has indirect access to all of the private members of the superclass.这段话第一句就直接了当说明了子类不能继承父类的私有成员。因此关于能不能继承,若还有疑问,请到java官网查找相关文档。