Can I do arithmetic operations on the Number baseclass?

Number does not have a + operator associated with it, nor can it since there is no operator overloading.

It would be nice though.

Basically, you are asking java to autobox a descedant of Number which happens to include Integer, Float and Double, that could be autoboxed and have a plus operator applied, however, there could be any number of other unknown descendants of Number that cannot be autoboxed, and this cannot be known until runtime. (Damn erasure)


Your problem is not really related to generics, rather to operators, primitives vs objects, and autoboxing.

Think about this:

public static void main(String[] args) {
    Number a = new Integer(2);
    Number b = new Integer(3);
    Number c = a + b;
}

The above does not compile

public static void main(String[] args) {
    Integer  a = new Integer(2);
    Integer b = new Integer(3);
    Number c = a + b;
}

The above does compile, but only because of autoboxing - which is kind of a hacky syntax glue introduced in Java 5, and only works (in compile time) with some concrete types : int-Integer for example.

Behind the scenes, the Java compiler is rewriting the last statement ("I must unbox a and b to apply the sum operator with primitive datatypes, and box the result to assign it to object c") thus:

    Number c = Integer.valueOf( a.intValue() + b.intValue() );

Java can't unbox a Number because it does not know at compile time the concrete type and hence it cannot guess its primitive counterpart.


You can do something like this

    class Example <T extends Number> {
        public Number add(T a, T b){
            return new Double(a.doubleValue() + b.doubleValue());
        }
    }