書上代碼示例:java
1 package com.learnJava.test; 2 3 /** 4 * @Author zhuchangli 5 * @Date 2019/9/14 6 **/ 7 class Game{ 8 Game(int i){ 9 System.out.println("Game constructor"); 10 } 11 } 12 13 class BoardGame extends Game{ 14 BoardGame(int i){ 15 super(i); 16 System.out.println("BoardGame constructor"); 17 } 18 } 19 public class Chess extends BoardGame{ 20 Chess(){ 21 super(11); 22 System.out.println("Chess constructor"); 23 } 24 25 public static void main(String [] args){ 26 Chess x = new Chess(); 27 } 28 }
結論:若是不在BoardGame() 中調用基類構造器,編譯器將抱怨沒法找到符合Game() 形式的構造器。spa
練習6:用Chess.java 來證實前一段話。code
註釋掉:BoardGame 類中的super(i) 便可證實。blog
練習7:(1)修改練習5,使A和B以帶參數的構造器取代默認構造器,爲C寫一個構造器,並在其中執行全部的初始化。繼承
個人答案:編譯器
package com.learnJava.test; /** * @Author zhuchangli * @Date 2019/9/14 **/ class ArtA{ ArtA(int i){ System.out.println("A constructor"); } } class ArtB extends ArtA{ ArtB(int i){ super(i); System.out.println("B constructor"); } } public class CartoonC extends ArtB{ CartoonC(int i){ super(i); System.out.println("C constructor"); } public static void main(String [] args){ //ArtB b = new ArtB(10); CartoonC c = new CartoonC(10); } }
參考答案:編譯
1 package com.learnJava.test; 2 3 /** 4 * @Author zhuchangli 5 * @Date 2019/9/14 6 **/ 7 class A7{ 8 A7(char c,int i){ 9 System.out.println("A7(char,int)"); 10 } 11 } 12 13 class B7 extends A7{ 14 B7(String d,float j){ 15 super(' ',10); 16 System.out.println("B7(String,j)"); 17 } 18 } 19 20 public class C7 extends A7{ 21 private char c; 22 private int j; 23 C7(char a,int i){ 24 super(a,i); 25 c = a; 26 j = i; 27 } 28 29 B7 b7 = new B7("hi",0.7f); 30 public static void main(String [] args){ 31 C7 c7 = new C7('a',100); 32 } 33 }
我未知的是:能夠在 C7類中 定義B7 類和 初始化。而C7類和B7類都是繼承的是 A7。class
練習8:(1)建立一個基類,它僅有一個非默認的構造器;再建立一個導出類,它帶有默認構造器和非默認構造器。在導出類的構造器中調用基類構造器。test
參考答案:float
1 package com.learnJava.test; 2 3 /** 4 * @Author zhuchangli 5 * @Date 2019/9/14 6 **/ 7 8 class A8{ 9 private char a; 10 private int i ; 11 A8(char c,int j){ 12 a = c; 13 i = j; 14 System.out.println("A8(char,int)"); 15 } 16 } 17 18 public class C8 extends A8{ 19 private char ch; 20 private int k; 21 C8(){ 22 super('z', 0); 23 System.out.println("C8()"); 24 } 25 C8(char a,int i){ 26 super(a,i); 27 ch = a; 28 k = i; 29 System.out.println("C8(char,int)"); 30 } 31 32 public static void main(String [] args){ 33 C8 c8 = new C8(); 34 C8 c81 = new C8('a',100); 35 } 36 }
未知點:在C8(),默認構造方法中不知道該如何調用基類方法。