1. 程式人生 > >JAVA中super和this呼叫建構函式

JAVA中super和this呼叫建構函式

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!