Type Inference from Assignment Context
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 the type variable isn’t used in any of the arguments or the method has no arguments? Suppose the method only has a parametric return type. The Java compiler is smart enough to look at the context in which the method is called. Specifically, if the result of the method is assigned to a variable, the compiler tries to make the type of that variable the parameter type. For example, in the following example, the generic method makeGen( ) has no arguments and it is like a factory for our Gen objects :
The compiler has, as if by magic, determined what kind of instantiation of Gen we want based on the assignment context. Before you get too excited about the possibilities, there’s not much you can do with a plain type parameter in the body of that method. For example, we can’t create instances of any particular concrete type T, so this limits the usefulness of factories.
Furthermore, the inference only works on assignment to a variable. Java does not try to guess the parameter type based on the context if the method call is used in other ways, such as to produce an argument to a method or as the value of a return statement from a method. In those cases, the inferred type defaults to type Object.
Program
Program Source
class Gen<T> { private T ty; void setT(T t) { ty=t; } T GetT() { return ty; } } public class Javaapp { static <T> Gen<T> makeGen() { return new Gen<T>(); } public static void main(String[] args) { Gen<Integer> gobj1 = makeGen(); Gen<String> gobj2 = makeGen(); gobj1.setT(50); gobj2.setT("Fifty"); System.out.println("gobj1 T : "+gobj1.GetT()); System.out.println("gobj2 T : "+gobj2.GetT()); } }