做項(xiàng)目的時(shí)候錯(cuò)認(rèn)為在子類(lèi)中修改從父類(lèi)繼續(xù)下來(lái)的變量值,會(huì)影響到其他繼承該變量的子類(lèi),實(shí)際上不是的,,每個(gè)繼承了這個(gè)變量的子類(lèi),相當(dāng)于拷貝了一份變量,,對(duì)變量的修改影響也僅限于自身,,不會(huì)影響到父類(lèi)的變量值,更不會(huì)影響到其他子類(lèi)對(duì)應(yīng)的變量值,。特意寫(xiě)的demo驗(yàn)證下: //父類(lèi) public abstract class AbstractParent { public int common = 1; public abstract void printCommon(); } 1 2 3 4 5 //子類(lèi)1 public class Child1 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } } 1 2 3 4 5 6 7 //子類(lèi)2 public class Child2 extends AbstractParent{ @Override public void printCommon() { System.out.print("common:" + common); } } 1 2 3 4 5 6 7 //主類(lèi) 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 執(zhí)行輸出的結(jié)果為: common:1,由此可見(jiàn)類(lèi)child1修改的是從父類(lèi)common變量的拷貝,不會(huì)影響父類(lèi)common的值 進(jìn)一步做驗(yàn)證,在子類(lèi)中聲明一個(gè)和父類(lèi)相同的變量并修改其值,,修改后的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 輸出結(jié)果: common:6 parent common:1 common:1 parent common:1 common:10 parent common:10 由此可見(jiàn),,如果在子類(lèi)中聲明了和父類(lèi)名稱(chēng)一樣的變量,則子類(lèi)中對(duì)自己聲明的變量的修改,,不影響父類(lèi)中改變量的值,,變量繼承的父類(lèi)和子類(lèi)內(nèi)存模型如下圖: 這里寫(xiě)圖片描述 博客二: 是同一個(gè),父類(lèi)和子類(lèi)共享同一個(gè)域 如下面的例子: 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... 這樣明白了吧
|
|
來(lái)自: 木三水0vosidma > 《java》