if/else语句在java构造函数中

App*_*sei 3 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;
}
Run Code Online (Sandbox Code Playgroud)

//塞特斯

  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;
}
Run Code Online (Sandbox Code Playgroud)

dur*_*597 7

您需要将它们放在构造函数中,否则数据也可能无效.当然,您可以通过在构造函数中调用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);
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ken 5

最好的办法是将if/else语句放在setter中,并使用构造函数中的setter.这样你就可以将你的逻辑放在一个地方,而且维护起来要容易得多.