轉載自:https://blog.csdn.net/u014042146/article/details/48374087,除了個別注釋稍作更改,其他沒變,代碼建議跑一遍,想清楚邏輯。
this 和super在構造函數中只能有一個,且都必須是構造函數當中的第一行。
super關鍵字,子類可以通過它調用父類的構造函數。
1、當父類的構造函數是無參構造函數時,在子類的構造函數中,就算不寫super()去調用父類的構造函數,編譯器不會報錯,因為編譯器會默認的去調用父類的無參構造函數。
class hood { public hood(){ System.out.println("1"); } } class hood2 extends hood{ public hood2(){ System.out.println("2"); } } public class TEST { public static void main(String[] args){ hood2 t = new hood2(); } }
這段代碼的運行結果是:1 2
2、當父類的構造函數是有參構造函數時,此時如果子類的構造函數中不寫super()進行調用父類的構造函數,編譯器會報錯,此時不能省去super()
class hood { public hood(int i){ System.out.println("1"+i); } } class hood2 extends hood{ public hood2(){ super(5); System.out.println("2"); } } public class TEST { public static void main(String[] args){ hood2 t = new hood2(); } }
這段代碼的運行結果是:15 2
再來是this關鍵字,可以理解為它可以調用自己的其他構造函數,看如下代碼:
class Father { int age; // 年齡 int hight; // 身體高度 public Father() { print(); this.age=20; //這里初始化 age 的值 } public Father(int age) { this(); // 調用自己的第一個構造函數,下面的兩個語句不執行的 this.age = age; print(); } public Father(int age, int hight) { this(age); // 調用自己第二個構造函數 ,下面的兩個語句不執行的 this.hight = hight; print(); } public void print() { System.out.println("I'am a " + age + "歲 " + hight + "尺高 tiger!"); } public static void main(String[] args) { new Father(22,7); } }
這段代碼的運行結果是:
I'am a 0歲 0尺高 tiger!
I'am a 022歲 0尺高 tiger!
I'am a 22歲 7尺高 tiger!
