簡體   English   中英

if / else語句在java構造函數中

[英]If/else statements inside a java constructor

當我在Setters中只有if / else條件時,該程序無效。 我得到了一個提示,我必須在構造函數中使用它們。 有人可以向我解釋..為什么?

另一個問題:您是否將if / else語句放在Constructor或Setters中?

//構造函數

   public Invoice(String partNumber, String partDescription, int quantity,
        double pricePerItem) {
    super();
    this.partNumber = partNumber;
    this.partDescription = partDescription;

    if (quantity <= 0)
        quantity = 0;
    else
        this.quantity = quantity;

    if (pricePerItem <= 0)
        pricePerItem = 0.0;
    else
        this.pricePerItem = pricePerItem;
}

//塞特斯

  public void setQuantity(int quantity) {
    if (quantity <= 0)
        this.quantity = 0;
    else
        this.quantity = quantity;
}

public double getPricePerItem() {
    return pricePerItem;
}

public void setPricePerItem(double pricePerItem) {

    if (pricePerItem != 0.0)
        this.pricePerItem = 0.0;

    else
        this.pricePerItem = pricePerItem;
}

您需要將它們放在構造函數中,否則數據也可能無效。 當然,您可以通過在構造函數中調用setter來避免冗余代碼!

他們在構造函數中不起作用的原因是因為你需要這樣做this.quantity = 0; quantity = 0;

從構造函數中調用setter的示例:

public Invoice(String partNumber, String partDescription, int quantity,
               double pricePerItem) {
    super();
    this.partNumber = partNumber;
    this.partDescription = partDescription;

    // call Setter methods from within constructor
    this.setQuantity(quantity);
    this.setPricePerItem(pricePerItem);
}

最好的辦法是將if / else語句放在setter中,並使用構造函數中的setter。 這樣你就可以將你的邏輯放在一個地方,而且維護起來要容易得多。

把if / else語句放在構造函數和setter中都經常使用。 它確保對象永遠不會處於無效狀態。

正如John3136在評論中指出的那樣,從構造函數中調用setter是一個好主意,以減少重復代碼的數量。

您的構造函數的if / else塊仍然存在錯誤。

  if (quantity <= 0)
    quantity = 0;    //  <-- this is setting the parameter passed to 0
else
    this.quantity = quantity;  // <-- this.quantity is only ever set if quantity is > 0.

你會想改變的身體ifthis.quantity或刪除else ,只是一直執行this.quantity = quantity后轉讓if

設計建議:當收到數量<0或價格<0而不是默認為0時,考慮拋出IllegalArgumentException。這取決於您的具體要求,但為-1對象創建發票似乎應該是一個錯誤。

我得到了一個提示,我必須在構造函數中使用它們。 有人可以向我解釋..為什么?

最有可能避免代碼重復。

另一個問題:您是否將if / else語句放在Constructor或Setters中?

即使你把它放在構造函數中,你也需要它們在setters中。

BTW if/else statements驗證

暫無
暫無

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

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