This question already has an answer here:
- What is a raw type and why shouldn't we use it? 15 answers
Please notice the code below doesn't compile, failing on the method result assignment: String s = a.method("abc");
.
The compilation error: incompatible types: java.lang.Object cannot be converted to java.lang.String
But, when changing A a
to A<?> a
or to A<Object> a
, the compilation passes.
* Please notice that the type <T>
in the method is different than the type <O>
in the class.
Any idea what the compilation error? Also, why the generic definition in variable a
solves the compilation issue?
class A<O>
{
O something;
<T> T method(T t)
{
return t;
}
static void testJavaStrangeGenericDefinitionBehavior()
{
A a = null;
String s = a.method("abc");
}
}