I was confused with my code that includes a generic method that takes no parameters, so what will be the return generic type of such a method, eg:
static <T> example<T> getObj() {
return new example<T>() {
public T getObject() {
return null;
}
};
}
and this was called via:
example<String> exm = getObj(); // it accepts anything String like in this case or Object and everything
the interface example's
defination is:
public interface example<T> {
T getObject();
}
My question:example<String> exm
is accepting String, Object and everything. So at what time generic return type is specified as String and how??
The compiler infers the type of T
from the concrete type used on the LHS of the assignment.
From this link:
If the type parameter does not appear in the types of the method arguments, then the compiler cannot infer the type arguments by examining the types of the actual method arguments. If the type parameter appears in the method's return type, then the compiler takes a look at the context in which the return value is used. If the method call appears as the righthand side operand of an assignment, then the compiler tries to infer the method's type arguments from the static type of the lefthand side operand of the assignment.
The example code in the link is similar to the one in your question:
public final class Utilities {
...
public static <T> HashSet<T> create(int size) {
return new HashSet<T>(size);
}
}
public final class Test
public static void main(String[] args) {
HashSet<Integer> hi = Utilities.create(10); // T is inferred from LHS to be `Integer`
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With