在創建新對象時,所有繼承下來的構造函數都會被繼承
example:
補充:如實例所示,Hippo 對象 IS-A Animal 同時也是IS-A Object,如果需要創建Hippo,也需要創建出Animal 以及Object的部分,這樣的過程被稱為“構造函數鏈(Constructor Chaining)” 。
1 public class Animal {
2 public Animal(){
3 System.out.println("Maka a animal");
4 }
5 }
1 public class Hippo extends Animal{
2 public Hippo(){
3 //super();默認添加,調用父類
4 System.out.println("make a Hippo");
5 }
6 }
1 public class TestHippo {
2
3 public static void main(String[] args) {
4 // TODO Auto-generated method stub
5 System.out.println("Starting...");
6 Hippo hippo=new Hippo();
7 }
8
9 }
順序執行
為什麼子類一定要訪問父類中的構造函數呢?
Plus example:
1 class Fu{
2 int x =30;
3 Fu()
4 {
6 System.out.println(x);
7 }
8 Fu(int x)
9 {
10 System.out.println(x);
11 }
12 }
13 class Zi extends Fu {
14 Zi(){
15 //seper();
16 //super(4); //指定訪問父類中帶有一個參數的構造函數
17 this(20);
18 System.out.println("zi ..."+x);
19 }
20 Zi(int x)
21 {
22 System.out.println("zi..."+x);
23 }
24
25 }
26 public class Single {
27 public static void main(String[] args) {
28 Zi z=new Zi();
29 //Zi z1=new Zi(3);
30 }
31 }
執行結果:

執行順序: