簡體   English   中英

如果重載構造函數,如何調用super(...)和this(...)?

[英]How to call both super(…) and this(…) in case of overloaded constructors?

我以前從未需要這樣做,但由於兩者都必須是構造函數中的“第一行”,應該如何解決它? 對於這樣的情況,最好的重構是什么?

這是一個示例:

public class Agreement extends Postable {


public Agreement(User user, Data dataCovered)
{
    super(user);
    this(user,dataCovered,null);

}

public Agreement(User user,Data dataCovered, Price price)
{
    super(user);

    if(price!=null)
        this.price = price;

    this.dataCovered = dataCovered;


}
   ...
}

super(user)的調用絕對必須。 在這種情況下如何處理“可選參數”? 我能想到的唯一方法就是重復,即根本不要稱之為(...)。 只需在每個構造函數中執行賦值。

你不能同時調用super(..)和this(...)。 你可以做的是重新設計你的overloadeded構造函數的結構,這樣最后一個被調用的將調用super(...)。 如果這不是一個選項,您將必須在每個構造函數中進行分配。

如果你調用this(user,dataCovered,null) ,將調用第二個構造函數,它將要做的第一件事就是調用超級構造函數。 所以行super(user); 在第一個構造函數中是不必要的。

在構造函數中,有(除了其他類似調用非超級或此內的實例方法)這三個限制:

  • 每個構造函數只能調用一次super(...)this(...)
  • super或者this總是必須是方法中的第一個語句
  • 如果您不提供任何這些,則在構造函數的開頭有一個隱式的super()

原因是對象只能創建一次。 super通過調用重載的構造函數來創建一個對象,而這是委托給同一個類的另一個構造函數。

正如另一個答案所說,在你的情況下,你不需要第一個super因為你的this語句委托給已經調用super(user)的另一個構造函數。

我將在類中的靜態方法中將構造函數中需要執行的邏輯分離出來,並將其稱為兩個構造函數,以避免重復。 但是,在您的情況下,您可以從第一個構造函數中跳過對super(user)的調用,第二個將為您調用它:)。 我會顛倒構造函數之間的“依賴關系”,如下所示:

public class Agreement extends Postable {


public Agreement(User user, Data dataCovered)
{
    super(user);
    setDataCovered(dataCovered);

}

public Agreement(User user, Data dataCovered, Price price)
{
    this(user, dataCovered);

    if(price!=null)
        setPrice(price);

}

private static void setDataCovered(Data dataCovered) {
     this.dataCovered = dataCovered;
}

private staitc void setPrice(Price price) {
     this.price = price;
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM