I have the following Java code that I tried out in JShell.
class X<A> {
A id(A a) {
return a;
}
}
Case 1
X<Integer> w = new X<Integer>();
w.id(5)
In this case, JShell prints just 5, as I had expected. I expect the identity function in w to be parameterized with type Integer
and thus expects nothing but a Integer
. Supplying variables that are not subtypes of Integers causes this function to error.
Case 2
X x = new X<Integer>();
x.id(5)
JShell does output 5, but along with 5, it also outputs this error message:
| Warning:
| unchecked call to id(A) as a member of the raw type X
| x.id(5)
| ^-----^
What does it mean by an unchecked call to id(A)? It doesn't seem to infer the type of x
to be X<Integer>
as I'm also able to run x.id("5")
with just a warning which is isn't possible in case 1. Does this mean the identity function in x
is polymorphic (with respect to the type of variable supplied)?
Case 3
X y = new X<>()
y.id(5)
X z = new X()
z.id(5)
This situation is identical to case 2. However, I am unable to wrap my mind around the code. What is the parameterized type of y? Are objects y and z identical apart from the fact that they are two separate objects?
I'm guessing the notion of type erasure is playing a part in this but am unable to truly understand it and explain the phenomenon above.