抽象类数学运算符和Java数字
这个问题是另一个问题的后续问题:Abstract class with default value
我试图定义一个抽象范围类,它将作为许多范围类的基本实现。预期用途与这个问题无关,但到目前为止,我已经:
/**
* Abstract generic utility class for handling ranges
*/
public abstract class Range<T extends Number> implements Collection<T>{
// Variables to hold the range configuration
protected T start;
protected T stop;
protected T step;
/**
* Constructs a range by defining it's limits and step size.
*
* @param start The beginning of the range.
* @param stop The end of the range.
* @param step The stepping
*/
public Range(T start, T stop, T step) {
this.start = start;
this.stop = stop;
this.step = step;
}
}
(上面省略了不相关的内容)
现在我想实现Collection
,所以我在我的抽象类中实现Size
,如下所示:
@Override
public int size() {
return (this.stop - this.start) / this.step;
}
但是Number
似乎对它的工作来说是普遍的。我需要在子类中实现这一点,还是有一种抽象的方法
# 1 楼答案
这应该是有效的:
见:http://docs.oracle.com/javase/8/docs/api/java/lang/Number.html#doubleValue
重要提示:如果您使用的数字实现需要比double更高的精度或更高的范围,则必须在子类中重写此方法。你应该把它添加到你的文档中