Reputation: 650
This is regarding a puzzling "incompatible types" error which is produced when compiling the following piece of code, after a small modification.
Here is the content of a minimalist class, which compiles without problems in both javac and IntelliJ:
public final class ChildClass extends ParentClass<Object> {
public void method() {
String value = stringList.get(0);
}
}
class ParentClass<T> {
protected final List<String> stringList = new ArrayList<String>();
}
After modifying the first line by removing <Object>
, compiling it with javac produces the following error message:
ChildClass.java:6: incompatible types
found : java.lang.Object
required: java.lang.String
String value = stringList.get(0);
^
1 error
A similar error message is produced by IntelliJ compiler as well.
Even though I understand the resulting code after the modification is not really recommended, I don't really understand why the String list is affected, although it should not depend on T
.
Upvotes: 3
Views: 1037
Reputation: 374
Java Language Specification 4.8:
The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.
This means that all generic members of a raw type (= Generic used without type parameters) are considered raw.
You could fix your example:
public final class ChildClass extends ParentClass {
public void method() {
String value = stringList.get(0);
}
}
class ParentClass<T> extends NonGenericGrandParent {
}
class NonGenericGrandParent {
protected final List<String> stringList = new ArrayList<String>();
}
Upvotes: 2