In the below program am passing 2 types parameters uisng single method. I am getting "The operator + is undefined for the argument type(s) T, K" while adding 2 parameters.
import java.util.*;
class Multipletypeparameters<T,K>{
T obj1;
K obj2;
public void setting(T obj1,K obj2){
this.obj1=obj1;
this.obj2=obj2;
}
public T add(){
//Here While adding I am getting The operator + is undefined for the argument type(s) T, K error
return obj1 + obj2;
}
}
public class MultipleTypeParametersExample {
public static void main(String[] args) {
MultipleTypeParametersExample<String,String> g1=new MultipleTypeParametersExample <String,String>();
g1.setting("A","B");
System.out.println(g1.add());
MultipleTypeParametersExample <Integer,Integer> g2=new MultipleTypeParametersExample <Integer,Integer>();
g2.setting(10,10);
System.out.println(g2.add());
}
}
+operator to "add" two instances of the generic typesTandK. Imagine you pass aCarand aBoatinstance forTandK- what do you expect the+to do?! A driving boat? A swimming car? And how would the compiler know that?+method is not defined forObject. What should happen if you create aMultipleTypeParametersExample<List, Set>?+operator is defined for primitive number types and Strings only. anything else needs a method defined in an interface where the implementing class knows what to do.