Java构造函数中的if / else语句 [英] If/else statements inside a java constructor

查看:280
本文介绍了Java构造函数中的if / else语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在二传手中只有if / else条件时,此程序无法正常工作。我得到的提示是,我也必须在构造函数中使用它们。有人可以向我解释..为什么?

This program wasn't working when I only had the if/else conditions in the Setters. I got a tip that I have to use them inside the Constructors too. Can someone explain to me.. why?

另一个问题:您是否将if / else语句放置在构造方法或设置方法中?

Another Question: Do you place the if/else statements inside the Constructor or 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;
}

// Setters

  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中的if / else语句,并在构造函数中使用setter。这样一来,您就可以将逻辑完全集中在一个地方,而且维护起来也容易得多。

Your best bet is to put the if/else statements in the setters and use the setters from within the constructor. That way you have your logic in exactly one place and it's much easier to maintain.

这篇关于Java构造函数中的if / else语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆