java - java 构造函数中的 if/else 语句

标签 java constructor

当我在 setter 中只有 if/else 条件时,这个程序无法运行。我得到一个提示,我也必须在构造函数中使用它们。谁能给我解释一下……为什么?

另一个问题:您是否将 if/else 语句放在 Constructor 或 Setter 中?

//构造函数

   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;
}

最佳答案

最好的办法是将 if/else 语句放在 setter 中,并在构造函数中使用 setter。这样一来,您的逻辑就在一个地方,而且更容易维护。

关于java - java 构造函数中的 if/else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202672/

相关文章:

java - 如何获取hyper-v虚拟机的总cpu使用率

Javax 验证不适用于值为数组或列表的 Hashmap

java - 显式扩展对象类并调用对象抛出错误的克隆方法

javascript - 原型(prototype):应用与调用、新建与创建

java - 如何在java中使用不同的泛型构造构造函数

dll - 首先调用 DllMain() 还是全局静态对象构造函数?

java - hibernate有哪些要点?

java - 使用运行时定义的配置按需实例化 Bean

javascript - Node - 工厂或构造函数,还是两者都不?

c++ - 无法理解类构造函数