Java Reference
In-Depth Information
String s1 = "Hello";
String s2 = passThrough(s1);
In this case, the argument type is inferred to be
String
, which is the
static type of the variable
s1
. This implies that the return type is also
String
. This is compatible with the assignment to
s2
and so the invoca-
tion is valid with an inferred type of
String
.
The following invocations of
passThrough
are also valid:
String s1 = "Hello";
Object o1 = passThrough(s1); // T => String
Object o2 = passThrough((Object) s1); // T => Object
In the first case the argument type is
String
and the return type is ex-
pected to be
Object
. The inferred type for
T
is again
String
, implying that
the return type is also
String
. This is compatible with assignment to the
Object
variable
o1
, so the invocation is valid, with an inferred type of
String
. In the second case the static type of the argument is
Object
(due
to the cast) and so the inferred type is also
Object
. This makes the re-
turn type
Object
, so again we have a compatible assignment and so a
valid invocation. In general, type inference has to find the most specific
type in the set of types that satisfy the constraints imposed by the type
variablesa non-trivial exercise.
Type inference is based on the static type of the argument expressions
that are being passed, not their dynamic types, so the following won't
compile:
String s1 = "Hello";
s1 = passThrough((Object) s1); // INVALID: won't compile