Java 定义构造函数的正确方法?

Java 定义构造函数的正确方法?,java,oop,constructor,Java,Oop,Constructor,我想知道用Java定义构造函数的正确方法。 这也许不是一个好问题,但仍然是 假设我有这个班: public class Element { private String value; private Date timestamp; public String getValue() { return value; } public void setValue(String value) { this.value = val

我想知道用Java定义构造函数的正确方法。 这也许不是一个好问题,但仍然是

假设我有这个班:

public class Element {
    private String value;
    private Date timestamp;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }

    public Element(String value, Date timestamp) {
        this.value = value;
        this.timestamp = timestamp;
    }
}
我可以使用setter定义构造函数吗

public Element(String value, Date timestamp) {
    setValue(value);
    setTimestamp(timestamp);
}

哪个设计更好?第一个似乎是标准,我也一直在使用它。

是的。您可以这样定义构造函数。我用swing按钮等工具做过几次,效果非常好。这是一种组织代码的简洁方法,尤其是在验证任何一个参数时

此外,它可能有助于继承,您只需要重写setter并使用超类的构造函数

所以,至少对我来说,第二种设计更好


你的问题完全合理

假设我们在setter中定义了一个约束

public class Person {
   private int weight = 0;

   public Person(int weight) {
        this.weight = weight;
   }

   public void setWeight(int weight) {
        if(weight > 200) throw new IllegalArgumentException("Weight unreasonable");
        this.weight = weight;
   }
}
现在,使用setter,我们可以向类引入过滤器、逻辑或行为。一个人的体重不能超过200磅。但使用构造函数时,不会应用权重规则。你可以做新人10000

因此,为了保存对象行为,建议在设置成员变量的值时在构造函数中使用setter

public Person(int weight) {
    setWeight(weight);
}

因此,构造函数不会破坏权重的预期行为

我宁愿使用后者,这使得setter方法上定义的任何行为都应用于构造函数参数,并保证成员变量的一致性。没有正确的方法,它们是您喜欢的,其他人可能喜欢的。此外,在某些情况下,使用setter获得相同的行为很有用,而在其他情况下,setter行为应该与初始化行为不同。同样,没有一种正确的方法。更好的设计是使对象不可变!完全删除setter并使字段成为最终字段。因此,根据du的答案[picate问题第二个问题不是首选!!实际上这是一个错误的建议,因为它依赖于副作用,副作用可以随子类的变化而变化。这是一个错误的建议,因为你依赖于副作用,副作用可以随子类的变化而变化