Can someone tell me why this code gives me a compile-error?
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;
}
}
Numberis not a generic class, so you can’t parameterize it:Further, the
+operator only works on primitive types likeint,long, etc., rather thanNumbersubtypes likeInteger,Long, etc. (EDIT: It will operate on these by unboxing, yes, but it cannot automatically box the result in the appropriate wrapper class.)(You’ve stumbled upon one of the reasons
Numberis a poor example of polymorphism. It really only performs object-to-primitive conversions.)