Hi all,
As a small exercise I am trying to devise a generic maths class that can add two numbers together either Integer, Float and Double types.
I have written the following code
class Test {
public static void main(String args[]) {
MathClass<Integer> integers = new MathClass<Integer>();
Integer i= new Integer(2);
System.out.println(integers.add(i,i));
}
}
class MathClass<T> {
public T add(T a, T b) {
return a + b;
}
public T subtract(T a, T b) {
return a - b;
}
public T multiply(T a, T b) {
return a * b;
}
public T divide(T a, T b) {
return a / b;
}
}
But I get a compile error which says that I can't use the + - * / operators on T.
Yet something like the following code works
public class Test2 {
public static void main(String[] args) {
Integer i = new Integer(2);
Integer o = new Integer(2);
System.out.println(i + o);
}
}
Is there a way to make the generic maths class work as I would like?