证明Java中子类继承了父类的private属性

 时间:2024-11-19 18:51:52

1、父类Father定义一个private int = 7;的成员变量。public class Father { private int i = 7;}

证明Java中子类继承了父类的private属性

2、子类Son继承父类Father 。public class Son extends Father {}

证明Java中子类继承了父类的private属性

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(); }}

证明Java中子类继承了父类的private属性

4、使用Debug模式观察实例化结果。可以看到Son里维护了一个i变量。然而,这并不能证明子类继承了父类私有属性。

证明Java中子类继承了父类的private属性

5、因此子类直接操作是不可以的,既然是父类的私有成员,那么就可以通过父类方法操作,下面在父类定义了get,set方法。public class Father { private int i = 7; public int getI() { return i; } public void setI(int i) { this.i = i; }}

证明Java中子类继承了父类的private属性

6、在主程序中通过get()拿到这个成员变量的值,并打印,如下图。

证明Java中子类继承了父类的private属性

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官网查找相关文档。

  • 原神千门虚舟怎么通关
  • 原神追叙之石怎么使用
  • 《原神》影狼丸认可任务攻略
  • 原神合成台如何更换人物
  • 原神无想刃狭间雷柱子解谜方法
  • 热门搜索
    婆娑怎么读 电脑休眠怎么唤醒 我的世界怎么做电梯 胃酸怎么办 august怎么读 上眼睑下垂怎么办 韭菜盒子怎么和面 青菜怎么炒好吃 苑怎么读 汽车怎么画