java课程课后作业04之动手动脑
1.繼承條件下的構造方法調用
先貼出實驗需要的代碼:
1 package TestJava; 2 3 class Grandparent 4 { 5 public Grandparent() 6 { 7 8 System.out.println("GrandParent Created."); 9 10 } 11 12 13 public Grandparent(String string) 14 { 15 16 System.out.println("GrandParent Created.String:" + string); 17 18 } 19 20 } 21 22 23 24 class Parent extends Grandparent 25 { 26 27 28 public Parent() 29 { 30 31 //super("Hello.Grandparent."); 32 33 System.out.println("Parent Created"); 34 35 // super("Hello.Grandparent."); 36 37 } 38 39 } 40 41 42 43 class Child extends Parent 44 { 45 46 47 public Child() 48 { 49 50 System.out.println("Child Created"); 51 52 } 53 54 } 55 56 57 58 public class TestInherits 59 { 60 61 62 public static void main(String args[]) 63 { 64 65 Child c = new Child(); 66 67 } 68 69 }我們在第一次運行的時候發現輸出順序是:
GrandParent Created
Parent Created
Child Created
結論1:當我們去運行代碼的時候,父類的構造函數會先于子類的構造函數。
然后,在當我們把子類中的父類的構造方法取消注釋,我們會發現同樣的結果,然后當我們把父類的構造方法放入子類的構造方法之后,我們會發現,代碼無法編譯通過,由此得到結論。
結論2:通過 super 調用基類構造方法,必須是子類構造方法中的第一個語句。
結論2的原因:由于父類的構造方法放在了子類的后面,如果一旦可以運行,則違反了結論1,所以編譯無法通過。
2.判斷對象是否可以轉換
貼出實驗代碼:
1 class Mammal{} 2 class Dog extends Mammal {} 3 class Cat extends Mammal{} 4 5 public class TestCast 6 { 7 public static void main(String args[]) 8 { 9 Mammal m; 10 Dog d=new Dog(); 11 Cat c=new Cat(); 12 m=d; 13 //d=m; 14 d=(Dog)m; 15 //d=c; 16 //c=(Cat)m; 17 18 } 19 }在沒有注釋的代碼編譯可以通過,當中可以看出父類可以直接對子類進行轉換,而子類如果要對父類進行轉換的話必須要在父類的前面加上子類的名字來進行強制轉換,否則編譯無法通過。
3.對于被重寫的父類如何被調用
貼出實驗代碼:
1 package TestJava1; 2 public class ParentChildTest { 3 public static void main(String[] args) { 4 Parent parent=new Parent(); 5 parent.printValue();//100 6 Child child=new Child(); 7 child.printValue();//200 8 9 parent=child; 10 parent.printValue();//200 11 12 parent.myValue++; 13 parent.printValue();//200 14 15 ((Child)parent).myValue++; 16 parent.printValue();//201 17 18 } 19 } 20 21 class Parent{ 22 public int myValue=100; 23 public void printValue() { 24 System.out.println("Parent.printValue(),myValue="+myValue); 25 } 26 } 27 class Child extends Parent{ 28 public int myValue=200; 29 public void printValue() { 30 System.out.println("Child.printValue(),myValue="+myValue); 31 } 32 }運行結果已經寫在了注釋的后面。
分析:parent.myValue++;此行代碼的結果是對子類的myValue進行編輯,而parent.printValue();卻是對父類的myValue數值進行輸出,代碼((Child)parent).myValue++;是對父類的的數值編輯,所以再次輸出的時候就是201.
結論1:當子類與父類擁有一樣的方法,并且讓一個父類變量引用一個子類對象時,到底調用哪個方法,由對象自己的“真實”類型所決定,這就是說:對象是子類型的,它就調用子類型的方法,是父類型的,它就調用父類型的方法。
結論2:如果子類與父類有相同的字段,則子類中的字段會代替或隱藏父類的字段,子類方法中訪問的是子類中的字段(而不是父類中的字段)。如果子類方法確實想訪問父類中被隱藏的同名字段,可以用super關鍵字來訪問它。
結論3:如果子類被當作父類使用,則通過子類訪問的字段是父類的!? ? ? ? ? ? ? ? ?就是這段代碼->?((Child)parent).myValue++;
轉載于:https://www.cnblogs.com/heiyang/p/9890601.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的java课程课后作业04之动手动脑的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 织梦教程
- 下一篇: JZOJ5944信标