From Oracle's documentation of Type Inference
Type inference is a Java compiler's ability to look at each method invocation and corresponding declaration to determine the type argument (or arguments) that make the invocation applicable. The inference algorithm determines the types of the arguments and, if available, the type that the result is being assigned, or returned. Finally, the inference algorithm tries to find the most specific type that works with all of the arguments.
To illustrate this last point, in the following example, inference determines that the second argument being passed to the pick method is of type Serializable:
static <T> T pick(T a1, T a2) { return a2; }
Serializable s = pick("d", new ArrayList<String>());
Why the algorithm tries to find the most specific type ?
Because assignment compatibility would make the invocation ambiguous if this rule were not enforced.
For instance, PrintStream defines print(Object)
and print(String)
if the rule of the most specific type were not enforced, print("bar")
could invoke print(Object)
instead of print(String
), which would be counterintuitive.
Note that type selection is based on compile-time types, so in the following example print(Object)
is invoked:
PrintStream out = ...;
Object bar = "bar";
out.print(bar);
out.print((Object)"foo");
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