做项目的时候错认为在子类中修改从父类继续下来的变量值,会影响到其他继承该变量的子类,实际上不是的,每个继承了这个变量的子类,相当于拷贝了一份变量,对变量的修改影响也仅限于自身,不会影响到父类的变量值,更不会影响到其他子类对应的变量值。特意写的demo验证下: //父类 public abstract class AbstractParent { public int common = 1; public abstract void printCommon(); } 1 2 3 4 5 //子类1 public class Child1 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } } 1 2 3 4 5 6 7 //子类2 public class Child2 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } } 1 2 3 4 5 6 7 //主类 public class MyTest { public static void main(String[] args) { Child1 child1 = new Child1(); child1.common = 6; Child2 child2 = new Child2(); child2.printCommon(); } } 1 2 3 4 5 6 7 8 9 10 11 执行输出的结果为: 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); } } 1 2 3 4 5 6 7 8 9 10 11 public class Child2 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } public void printParentCommon(){ System.out.print("parent common:" + super.common); } } 1 2 3 4 5 6 7 8 9 10 11 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(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 输出结果: common:6 parent common:1 common:1 parent common:1 common:10 parent common:10 由此可见,如果在子类中声明了和父类名称一样的变量,则子类中对自己声明的变量的修改,不影响父类中改变量的值,变量继承的父类和子类内存模型如下图: 这里写图片描述 博客二: 是同一个,父类和子类共享同一个域 如下面的例子: class Father { int x; } class Children extends Father { void cal() { ++x; System.out.println("x of class Father: " + super.x); System.out.println("x of children: " + x); } } public class test { public static void main(String[] args) { new Children().cal(); } } 输出: x of class Father: 1 x of children: 1 Press any key to continue... 这样明白了吧
|
|
来自: 木三水0vosidma > 《java》