做项目的时候错认为在子类中修改从父类继续下来的变量值,会影响到其他继承该变量的子类,实际上不是的,每个继承了这个变量的子类,相当于拷贝了一份变量,对变量的修改影响也仅限于自身,不会影响到父类的变量值,更不会影响到其他子类对应的变量值。特意写的demo验证下:
//父类
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
由此可见,如果在子类中声明了和父类名称一样的变量,则子类中对自己声明的变量的修改,不影响父类中改变量的值,变量继承的父类和子类内存模型如下图: