Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use generics in Java with language operators and generic class extending Number

I would like to perform an operation on two generics argument of the same type both extending Number.

Is it Possible? I always used to call methods on generic arguments, but seems there is some problem using operators (The operator + is undefined for the argument type(s) T, T).

public static <T extends Number> T sum(T a, T b){
    return a+ b;
}

What am I doing wrong?

EDIT: I try to improve a little bit my question. I understood that operators are not defined for type Number. It's a bit sad this thing because it would be nice to perform such an operation without introducing new interfaces like suggested by @Victor Sorokin.

But I still don't understand one thing: if operators are not implemented in the class Number, then at least in Double class should be implemented because I can use + operator with double. Neither these line of code will compile:

public static <T extends Double> T sum(T a, T b){

    T c = a +b;
}

why?

like image 628
Heisenbug Avatar asked Jul 06 '11 18:07

Heisenbug


People also ask

Can a generic class be extended?

We can add generic type parameters to class methods, static methods, and interfaces. Generic classes can be extended to create subclasses of them, which are also generic.

Can generics take multiple type parameters?

Multiple parameters You can also use more than one type parameter in generics in Java, you just need to pass specify another type parameter in the angle brackets separated by comma.

What is the use of generic methods and generic classes in Java?

Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.


1 Answers

It's not possible because Number doesn't have a + operator associated with it. In particular, you can't do this:

Number a = new Integer(1);
Number b = new Integer(2);
Number c = a + b;
like image 105
thomson_matt Avatar answered Oct 11 '22 12:10

thomson_matt