2016-07-07 28 views
4

所以我們可以說我有A類,它是這樣定義的:如何處理繼承鏈中的默認值而不寫入重複代碼?

public class A{ 
    private int x; 

    public A(){ 
     this(13); 
    } 
    public A(int x){ 
     this.x = x; 
    } 
} 

然後,我有一個B類需要實現Y,所以是這樣的:

public class B extends A{ 
    private int y; 

    public B(){ 

    } 
    public B(int x){ 
     this(x, 0); 
    } 
    public B(int x, int y){ 
     super(x); 
     this.y = y; 
    } 
} 

我的問題是:我在做什麼public B()?我打電話給super(),以便A分配默認值/做任何事情,然後在該構造函數中執行另一個this.y = y,或者我打電話給this(13)

這兩種方法似乎都需要一些不好的做法。一個人在兩個地方寫this.y = y。另一個需要我重複默認值,並且每次更改默認值時都需要更改。

+0

您不需要做任何事情。 'B()'隱式調用'super()',所以'A()'被調用。 –

+0

但是如果我什麼都不做,我仍然需要給y一個默認值,這就是問題所在。我最終不得不這樣做,再次,當我已經做到了。 – WinterDev

+0

哦,對。抱歉。沒有發現你正在分配'y'。所以,你只需要在'B()'中分配'y'。 –

回答

0

如果在構造函數的第一行沒有調用繼承的構造函數,那麼將會調用繼承類的默認構造函數。如果沒有默認的構造函數,那麼你將不得不在構造函數的第一行定義它應該使用的超級構造函數。

public class A{ 

    public A(){ 

    } 

    public A(String text){ 

    } 

} 

public class B extends A{ 

    public B(){ 
     //having nothing is same as super(); 
     //here you can also call the other constructor 
     //super(""); is allowed 
    } 

    public B(String text){ 
     //having nothing is same as super(); 
     //but if you add a super(text) then you set this instance to super(text); instead 
    } 

} 

public class C{ 

    public C(String text){ 

    } 

} 

public class D extends C{ 

    public D(){ 
     super();// this is incorrect and will not compile 
    } 

    public D(String text){ 
     super(text);//this is fine 
    } 

} 

希望這對我有所幫助。

1

如果這些字段不是最終的,您可以在聲明它們的位置分配默認值。所以代碼將如下所示:

class A{ 
    private int x = 13; 
    public A(){ 
    //use default value for x 
    } 
    public A(int x){ 
    this.x = x; 
    } 
} 

class B extends A { 
    private int y = 0; 
    public B(){ 
    //use default value for x and y 
    } 
    public B(int x){ 
    super(x); 
    //use default value for y 
    } 
    public B(int x, int y){ 
    super(x); 
    this.y = y; 
    } 
} 
+0

正如我在評論中所說的,我的例子是另一組父類/子類的極其簡化的版本,因爲默認的構造函數執行了很多難以在實際構造函數之外實現的事情,所以在外面聲明它是不合理的。我想我的帖子應該更精確。此外,這是一個家庭作業問題,所以我無法編輯父類的內容。 – WinterDev

+0

@WinterDev然後我會去'super(); this.y = y;'以避免在B中重複x的默認值。 – assylias