[英]Incompatible types error when inheriting without specifying generic type of parent class
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: 这是一个极简主义类的内容,它在javac和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: 通过删除
<Object>
修改第一行后,使用javac编译它会产生以下错误消息:
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. IntelliJ编译器也会生成类似的错误消息。
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
. 虽然我不太了解修改后得到的代码,但我真的不明白为什么String列表会受到影响,尽管它不应该依赖于
T
Java Language Specification 4.8 : Java语言规范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.
未从其超类或超接口继承的原始类型C的构造函数(第8.8节),实例方法(第8.4节,第9.4节)或非静态字段(第8.3节)M的类型是对应的原始类型在对应于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>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.