2016-02-01 315 views
0

我的家庭作業有這個奇怪的問題。下面有一個類聲明。在與超類構造函數不同的子類中定義構造函數?

public class A { 
private String str; 
private int num; 
    public A (String str, int num) { 
    this.str = str; 
    this.num = num; 
} 

現在我需要的是從A類繼承的子類的實現,卻有着不同的構造函數,像這樣:

public class B extends A { 
private String str1; 
    public B (String str, String str1) {...} 

// this is where the editor shows an error because class B constructor arguments are 
// different from the arguments in the class A constructor 

但我需要這種構造是不同的。我怎樣才能做到這一點?

回答

2

您需要調用父類的構造函數明確:

public class B extends A { 
private String str1; 
    public B (String str, String str1) { 
     super(str,0); 
     //do what you want... 
    } 
+0

謝謝老兄,我不知道我們可以給super();像這樣的論據(即0),最後一件事情,在超級論據中'0'代表什麼? –

+1

構造函數**不能**被覆蓋。 –

+0

@FabioÇimo0 ist一個int,超級構造函數所需的第二個參數。 –

1

必須使用super()聲明:

public B (String str, String str1) { 

    //0 is the second int argument of the class A constructor 
    super(str, 0); 

    //do something with the str1 
} 

因爲你A類沒有了的默認沒有參數 構造函數由編譯器創建,如果你沒有在類

+0

對,它可以工作,但是'0'代表super()裏面代表什麼? –

+0

0是類A構造函數的第二個int參數:** num變量** ..根據您的示例邏輯,您必須決定將什麼int作爲參數傳遞 –

2

首先你的基類的定製構造函數中定義紐約 構造函數,但不列入有默認情況下,這會導致編譯錯誤。派生類將在派生類構造函數的第一行中調用基類的隱式默認構造函數,或者可以調用必要的基類構造函數(super(..))取決於您的需要,然後調用構造函數體。 因此,擁有不同的構造函數並不是問題。

相關問題