1. 程式人生 > >子類繼承和呼叫父類的構造方法

子類繼承和呼叫父類的構造方法

1. 如果子類沒有定義構造方法,則呼叫父類的無引數的構造方法,.
2. 如果子類定義了構造方法,不論是無引數還是帶引數,在建立子類的物件的時候,首先執行父類無引數的構造方法,然後執行自己的構造方法。
3. 如果子類呼叫父類帶引數的構造方法,可以通過super(引數)呼叫所需要的父類的構造方法,切該語句做為子類構造方法中的第一條語句。
4. 如果某個構造方法呼叫類中的其他的構造方法,則可以用this(引數),切該語句放在構造方法的第一條.
說白了:原則就是,先呼叫父親的.(沒有就預設調,有了就按有的調,反正只要有一個就可以了.)
package test;
class Father{
String s = "Run constructor method of Father";
public Father(){
   System.out.println(s);
}
public Father(String str){
   s= str;
   System.out.println(s);
}
}
class Son extends Father{
String s= "Run constructor method of son";
public Son(){
   //實際上在這裡加上super(),和沒加是一個樣的
   System.out.println(s);
}
public Son(String str){
   this();//這裡呼叫this()表示呼叫本類的Son(),因為Son()中有了一個super()了,所以這裡不能再加了。
   s = str;
   System.out.println(s);
}
public Son(String str1, String str2){
   super(str1+" "+str2);//因為這裡已經呼叫了一個父類的帶引數的super("---")了,所以不會再自動呼叫了無引數的了。
   s = str1;
   System.out.println(s);
}
}
public class MyClass9 {
public static void main(String[] args){
   Father obfather1 = new Father();
   Father obfather2 = new Father("Hello Father");
   Son obson1 = new Son();
   Son obson2 = new Son("hello son");
   Son obson3 = new Son("hello son","hello father");
  
}
}
===============
結果:
Run constructor method of Father
Hello Father
Run constructor method of Father
Run constructor method of son
Run constructor method of Father
Run constructor method of son
hello son
hello son hello father
hello son