【发布时间】:2015-11-15 10:23:11
【问题描述】:
假设我有这个代码:
public class Car {
private int fuel;
public Car(int fuel) {
if (fuel < 0) {
throw new IllegalArgumentException("Can't be negative");
}
this.fuel = fuel;
}
public void setFuel(int fuel) {
if (fuel < 0) {
throw new IllegalArgumentException("Can't be negative");
}
this.fuel = fuel;
}
我的问题是,我能否避免在构造函数和设置器中重复代码?
【问题讨论】:
-
通过从构造函数调用setter? (请注意,您可能希望将 setter 设为 final 以避免calling an overridable method from the constructor。)
标签: java