这是关于一个令人费解的“不兼容类型”错误,该错误是在编译以下代码时经过小的修改后产生的。
下面是一个极简类的内容,在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>();
}
通过删除 <Object>
修改第一行后,使用 javac 编译它会产生以下错误消息:
ChildClass.java:6: incompatible types
found : java.lang.Object
required: java.lang.String
String value = stringList.get(0);
^
1 error
IntelliJ 编译器也会生成类似的错误消息。
虽然我理解修改后的结果代码并不是真的推荐,但我真的不明白为什么String列表会受到影响,虽然它不应该依赖于T
。 .
最佳答案
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.
这意味着原始类型的所有泛型成员(= 没有类型参数使用的泛型)都被认为是原始的。
你可以修正你的例子:
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>();
}
关于java - 在不指定父类的泛型类型的情况下继承时出现不兼容类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340430/