3 回答

TA贡献2039条经验 获得超7个赞
Number没有关联的+运算符,也没有,因为没有运算符重载。
那就太好了。
基本上,您是在要求Java自动对Number的后代进行自动装箱,该后代恰好包括Integer,Float和Double,可以自动装箱并应用加号运算符,但是,可能有Number的许多其他未知后代无法自动装箱,直到运行时才能知道。(该死的删除)

TA贡献1827条经验 获得超8个赞
您的问题与泛型并没有真正的关系,而是与运算符,原语与对象以及自动装箱有关。
考虑一下:
public static void main(String[] args) {
Number a = new Integer(2);
Number b = new Integer(3);
Number c = a + b;
}
上面没有编译
public static void main(String[] args) {
Integer a = new Integer(2);
Integer b = new Integer(3);
Number c = a + b;
}
上面的代码确实可以编译,但这仅是由于自动装箱-这是Java 5中引入的一种骇人听闻的语法胶,并且仅在某些具体类型下(在编译时)有效,例如int-Integer。
在后台,Java编译器正在重写最后一条语句(“我必须取消装箱a并b应用具有原始数据类型的sum运算符,然后将结果装箱以将其分配给对象c”),因此:
Number c = Integer.valueOf( a.intValue() + b.intValue() );
Java无法解包a,Number因为它在编译时不知道具体类型,因此无法猜测其原始对应物。

TA贡献1810条经验 获得超5个赞
是的,内森是正确的。如果您想要这样的东西,您必须自己编写
public class Example <T extends Number> {
private final Calculator<T> calc;
public Example(Calculator<T> calc) {
this.calc = calc;
}
public T add(T a, T b){
return calc.add(a,b);
}
}
public interface Calculator<T extends Number> {
public T add(T a, T b);
}
public class IntCalc implements Calculator<Integer> {
public final static IntCalc INSTANCE = new IntCalc();
private IntCalc(){}
public Integer add(Integer a, Integer b) { return a + b; }
}
...
Example<Integer> ex = new Example<Integer>(IntCalc.INSTANCE);
System.out.println(ex.add(12,13));
太糟糕了,Java没有类型类(Haskell)或隐式对象(Scala),此任务将是一个完美的用例...
添加回答
举报