繁体   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