我正在尝试编写一些代码,使我能够对“T extends Number”对象实例执行基本数学运算。它需要能够处理任何数字类型的子类Number
.
我知道下面的一些类型Number
have .add()
内置方法,有些甚至有.multiply()
方法。我需要能够将任何可能类型的两个通用变量相乘。我搜索了又搜索,但无法得出任何明确的答案。
public class Circle<T extends Number> {
private T center;
private T radius;
private T area;
// constructor and other various mutator methods here....
/**
The getArea method returns a Circle
object's area.
@return The product of Pi time Radius squared.
*/
public Number getArea() {
return 3.14 * (circle.getRadius()) * (circle.getRadius());
}
任何帮助将非常感激。泛型是我学习Java中遇到的最困难的事情。我不介意做跑腿工作,因为这样我可以学得更好,所以即使是在正确的方向上的强项也会非常有帮助。
您需要做的是使用双精度值Number
。但是,这意味着您无法退回Number
type.
public double getArea()
{
return 3.14 *
(circle.getRadius().doubleValue()) *
(circle.getRadius().doubleValue());
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)