我正在尝试实现一个“Range”类(在 Java 中)为它包装的 int 值提供边界强制功能。我希望它的每个子类都定义自己的最小/最大界限,而不必重写执行这些界限的逻辑。这是一个例子:
public abstract class Range {
// I would like each derived class to possess its own distinct instances of the
// min/max member data
protected static final int MIN_VAL;
protected static final int MAX_VAL;
protected int _value;
public void set (int newVal) {
// Range check the input parameter
// this should use the min/max bounds for the object's most derived class
if (newVal < MIN_VAL || newVal > MAX_VAL) {
throw new InvalidParameterException("`newVal` is out of range");
}
this._value = newVal;
}
public int get() {
return this._value;
}
}
// This class should limit its wrapped value to values between 1 and 6 inclusively
public class Die extends Range {
public Die() {
MIN_VAL = 1;
MAX_VAL = 6;
this.set (1);
}
}
显然这个实现不起作用,但我怎样才能实现我的目标呢?在不重复大部分逻辑的情况下这是否可能?