在Number的通用子类上使用加法运算符

Lex*_*ito 0 java generics

有人能告诉我为什么这段代码给我一个编译错误?

public class Main {

    public static void main(String[] args) {
        System.out.println(sum(2, 6.9));
    }

    public static <T extends Number<T>> T sum(T a, T b) {
        T result = a + b;      // compile-error here
        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

Ala*_*ger 5

Number 不是泛型类,因此您无法对其进行参数化:

public abstract class Number implements java.io.Serializable {
...
}
Run Code Online (Sandbox Code Playgroud)

此外,+运营商只能在原始的类型,如int,long等,而不是Number像亚型Integer,Long等.(编辑:它将被拆箱这些操作,是的,但它不能自动框结果在适当的包装类)

(您偶然发现其中一个原因Number是多态性的一个不好的例子.它实际上只执行对象到原始的转换.)