2017-07-24 82 views
2

我想了解Java構造函數super()。讓我們來看看以下課程:瞭解Java超級()構造函數

class Point { 
    private int x, y; 

    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public Point() { 
     this(0, 0); 
    } 
} 

該課程將編譯。如果我們創建一個新的Point對象說Point a = new Point();沒有參數的構造函數將被調用:Point()

糾正我,如果我錯了,在做this(0,0)之前,Class構造函數將被調用,只有Point(0,0)將被調用。 如果這是真的,說默認調用super()是否正確?

現在,讓我們看看相同的代碼與一個小的變化:現在

class Point { 

     private int x, y; 

     public Point(int x, int y) { 
      this.x = x; 
      this.y = y; 
     } 

     public Point() { 
      super(); // this is the change. 
      this(0, 0); 
     } 
    } 

,代碼將無法編譯,因爲this(0,0)不在構造函數的第一線。這是我感到困惑的地方。爲什麼代碼不能編譯?無論如何都不會調用super()? (如上所述的類構造函數)。

+0

點不是子類。想象一下,如果我們有一個子類PrettyPoint,那麼PrettyPoint(){super(0,0); }會從上面調用Point(int x,int y)。 – ZeldaZach

+1

這將幫助你理解:https://stackoverflow.com/questions/10381244/why-cant-this-and-super-both-be-used-together-in-a-constructor –

+0

@ZeldaZach一切都是一個子類'對象'。 –

回答

4

您還可以從同一個構造函數this()super()但不能同時使用。當您撥打this()時,super()會自動從其他構造函數(您使用this()調用的函數)中調用。

+0

因此,我有超級()的2個電話。謝謝。 – Romansko

+1

@Rom如果代碼可以編譯,那會是結果之一,是的。 –

1

通過調用this(...),您不得不在您要調用的構造函數中調用超級構造函數(如果存在)。

調用this(...)super(...)始終是您在構造函數中調用的第一個方法。

編輯

class Point { 
    private int x, y; 

    public Point(int x, int y) { 
     super(...); //would work here 
     this.x = x; 
     this.y = y; 
    } 

    public Point() { 
     this(0, 0); //but this(...) must be first in a constructor if you want to call another constructor 
    } 
} 
+0

這正是我的觀點。如果我被迫調用超級構造函數,如果我通過super()顯式調用它,然後調用這個(..),會有什麼不同? – Romansko

+1

作爲第二種方法,您不能打電話給super/this。如果你想調用一個超級構造函數,你需要在你調用的構造函數中完成。 – Cedric

5

this(0, 0);將調用,同一個類的構造函數和super()會調用Point類的超/父類。

現在,代碼將不會編譯,因爲此(0,0)不在構造函數的第一行 中。這是我感到困惑的地方。爲什麼代碼不會 編譯?不是super()被調用嗎?

super()必須構造的第一行,並且還this()必須在構造函數中的第一行。所以兩者都不能在第一行(不可能),也就是說,我們不能在構造函數中添加兩者。

作爲一個關於你的代碼explonation:

this(0, 0);將調用採用兩個參數(在Point類)的構造函數和兩個參數的構造函數會調用到super()隱式(因爲你沒有明確地稱呼它)。

4

把超級()放在你的第一個構造函數中,它應該工作。

class Point { 
 

 
     private int x, y; 
 

 
     public Point(int x, int y) { 
 
      super(); // this is the change. 
 
      this.x = x; 
 
      this.y = y; 
 
     } 
 

 
     public Point() { 
 
      
 
      this(0, 0); 
 
     } 
 
    }

1

構造函數可以使用方法調用super()來調用超類的構造函數。只有約束是它應該是第一個陳述。

public Animal() { 
    super(); 
    this.name = "Default Name"; 
} 

這段代碼會編譯嗎?

public Animal() { 
    this.name = "Default Name"; 
    super(); 
} 

答案是NO 。應始終在構造函數的第一行調用super()