My problem is with the return statement in each method,the error in netbeans says:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - bad operand types for binary operator '+' first type: T second type: T at GenericMath.add(GenericMath.java:8) at GenericMath.main(GenericMath.java:20)
public class GenericMath<T> {
public T a,b;
public T add() {
return a+b;
}
public T multiply() {
return (a*b);
}
public static <T> void main(String[] args) {
GenericMath<Integer> x=new GenericMath<Integer>();
x.a=5;
x.b=10;
int z=x.add();
GenericMath<Double> y = new GenericMath<Double>();
y.a = 5.5;
y.b = 10.2;
double g=y.multiply();
}
}
The compiler doesn't know that you can multiply and add T
values - it's not the return
part which the problem, it's the expression itself. You'll see the same effect if you split the two parts:
T result = a + b;
return result;
It will be the first line that fails - and there's no particularly clean answer to this. Generics just aren't built for this sort of work in Java. What you could do is have:
public abstract class GenericMath<T extends Number> {
public abstract T add(T a, T b);
public abstract T multiply(T a, T b);
// etc
}
public final class IntegerMath extends GenericMath<Integer> {
public Integer add(Integer a, Integer b) {
return a + b;
}
// etc
}
... and similar classes for DoubleMath
etc.
Then:
// Alternatively, have a static factory method in GenericMath...
GenericMath<Integer> math = new IntegerMath();
int x = math.add(5, 2);
See more on this question at Stackoverflow