2016-01-29 32 views
4

試圖瞭解super()方法何時調用。在下面的代碼中,Child類有一個沒有參數的構造函數,所以編譯器不能插入super()。那麼如何調用父構造函數。當super()在下面的代碼中調用時

public class Parent 
{ 
    public Parent() 
    { 
     System.out.println("In parent constructor"); 
    } 
} 


public class Child extends Parent 
{ 
private int age; 

public Child() 
{ 
    this(10); 
    System.out.println("In child constructor with no argument"); 
} 

public Child(int age) 
{ 
    this.age = age; 
    System.out.println("In child constructor with argument"); 
} 

public static void main(String[] args) 
{ 
    System.out.println("In main method"); 
    Child child = new Child(); 
} 

} 

輸出:

In main method 

In parent constructor 

In child constructor with argument 

In child constructor with no argument 
+0

this(10)只能用於調用當前的類(Child)構造函數。 – Bikku

+1

你能否在調試模式下運行你的程序?它會幫助你理解輸出。 – Bikku

回答

6

這裏是發生了什麼:

public class Parent 
{ 
    public Parent() 
    { 
     System.out.println("In parent constructor"); // 4 <------ 
    } 
} 


public class Child extends Parent 
{ 
    private int age; 

    public Child() 
    { 
     this(10); // 2 <------ 
     System.out.println("In child constructor with no argument"); // 6 <------ 
    } 

    public Child(int age) 
    { 
     // 3 -- implicit call to super() <------ 
     this.age = age; 
     System.out.println("In child constructor with argument"); // 5 <------ 
    } 

    public static void main(String[] args) 
    { 
     System.out.println("In main method"); // 1 <------ 
     Child child = new Child(); 
    } 
} 
1

super()任何構造函數的第一行之前隱式調用,除非明確要求super()或過載本身,或者班級是java.lang.Object.

0

的答案,我想澄清,我認爲重要的是這個問題的幾件事情之前:

  • 當你不聲明爲一個類的構造函數的Java編譯器建立在編譯時間默認構造函數。

  • 當我們有一個不調用它的父構造函數的子類。同樣,Java爲父級構建默認的構造函數,然後執行子類的構造函數(因爲當孩子創建其父級時,它的實例爲firstable)。

因此,在這種情況下:

1)執行公共主要方法。 2)新增子項的實例 2.1)'構建子構造函數',但第一個Java編譯器爲其父創建默認構造函數。 2.2)構建孩子(不接收參數的孩子) 3)使用默認構造函數(previous constr)中的age參數執行第二個構造方法。

我希望這會有所幫助。

相關問題