子类继承父类的变量和父类原有变量的关系
2015-08-13 23:20
477 查看
做项目的时候错认为在子类中修改从父类继续下来的变量值,会影响到其他继承该变量的子类,实际上不是的,每个继承了这个变量的子类,相当于拷贝了一份变量,对变量的修改影响也仅限于自身,不会影响到父类的变量值,更不会影响到其他子类对应的变量值。特意写的demo验证下:
执行输出的结果为: common:1,由此可见类child1修改的是从父类common变量的拷贝,不会影响父类common的值
进一步做验证,在子类中声明一个和父类相同的变量并修改其值,修改后的demo为:
输出结果:
common:6
parent common:1
common:1
parent common:1
common:10
parent common:10
由此可见,如果在子类中声明了和父类名称一样的变量,则子类中对自己声明的变量的修改,不影响父类中改变量的值,变量继承的父类和子类内存模型如下图:
//父类 public abstract class AbstractParent { public int common = 1; public abstract void printCommon(); }
//子类1 public class Child1 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } }
//子类2 public class Child2 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } }
//主类 public class MyTest { public static void main(String[] args) { Child1 child1 = new Child1(); child1.common = 6; Child2 child2 = new Child2(); child2.printCommon(); } }
执行输出的结果为: common:1,由此可见类child1修改的是从父类common变量的拷贝,不会影响父类common的值
进一步做验证,在子类中声明一个和父类相同的变量并修改其值,修改后的demo为:
public class Child1 extends AbstractParent{ int common = 10; @Override public void printCommon() { System.out.print("common:" + common); } public void printParentCommon(){ System.out.print("parent common:" + super.common); } }
public class Child2 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } public void printParentCommon(){ System.out.print("parent common:" + super.common); } }
public class MyTest { public static void main(String[] args) { Child1 child1 = new Child1(); child1.common = 6; Child2 child2 = new Child2(); Child2 child3 = new Child2(); child3.common = 10; //打印child1 child1.printCommon(); System.out.print("\n"); child1.printParentCommon(); System.out.print("\n"); //打印child2 child2.printCommon(); System.out.print("\n"); child2.printParentCommon(); //打印child3 System.out.print("\n"); child3.printCommon(); System.out.print("\n"); child3.printParentCommon(); } }
输出结果:
common:6
parent common:1
common:1
parent common:1
common:10
parent common:10
由此可见,如果在子类中声明了和父类名称一样的变量,则子类中对自己声明的变量的修改,不影响父类中改变量的值,变量继承的父类和子类内存模型如下图:
相关文章推荐
- IOS开发常用设计模式
- hdu 1013 Digital Roots(数论 模拟)
- 外观模式 Facade
- 小tip:中文英文左右padding一致两端对齐实现
- [推荐算法]Pearson Correlation Similarity 的python实现
- opencv中的机器学习
- Windows 10 Mobile 安装 apk
- 注册美国公司
- 编写高质量代码改善C#程序的157个建议——建议20:使用泛型集合代替非泛型集合
- SDL事件查询函数:SDL_PeepEvents()
- [机器学习]opencv
- ggplot2——玫瑰图
- 网络编程01---计算机网络基础
- noip1997 棋盘 (数列求和)
- Uva 673 Parentheses Balance
- [2015-08-10] python021
- 读《javascript权威指南》第五版 第七章 对象与数组
- 在intellj idea下用sbt的坑
- MapReduce入门例子
- 数三退一问题 java