Type Inference from Arguments
Generally generic method infer its type from its argument. For example , in the following generic method showAndGetV( ) calls look like normal method calls.
But what if there is more than one argument? For example, following generic method showAndGetV( ) contain two arguments :
All looks well when we give it two identical types. For example :
But what does it make of the different type of arguments ? For example :
In this case, the Java compiler does something really smart. It climbs up the argument type parent classes, looking for the nearest common supertype. Java also identifies the nearest common interfaces implemented by both of the types. It identifies that both the Integer and the Float types are subtypes of the Number type. It also recognizes that each of these implements (a certain generic instantiation of) the Comparable interface. Java then effectively makes this combination of types the parameter type of V for this method invocation. The resulting type is, to use the syntax of bounds, Number & Comparable. What this means to us is that the result type V is assignable to anything matching that particular combination of types.
The last two statements says that we can work with our Integer and our Float at the same time only if we think of them as Numbers or Comparables, which makes sense. The return type has become a new type, which is effectively a Number or Comparable . This same inference logic works with any number of arguments. But to be useful, the arguments really have to share some important common supertype or interface. If they don’t have anything in common, the result will be their de facto common supertype, the Object type. For example, the nearest common supertype of a String and a Integer is Object along with the Comparable interface. There’s not much a method could do with a type lacking real bounds anyway.
Program
public class Javaapp { static <V> V showAndGetV(V v1,V v2) { System.out.println("v1 : " + v1.getClass().getName()); System.out.println("v2 : " + v2.getClass().getName()); return v1; } public static void main(String[] args) { Number n = showAndGetV(200,15.5f); Comparable c = showAndGetV(200,15.5f); } }