java - 在不指定父类的泛型类型的情况下继承时出现不兼容类型错误

标签 java generics types

这是关于一个令人费解的“不兼容类型”错误,该错误是在编译以下代码时经过小的修改后产生的。

下面是一个极简类的内容,在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/

相关文章:

java - 如何填充和访问 3 维数组列表的任何元素

java - 在 selenium 中设置自定义浏览器配置文件

java - 在 Websphere 7 中使用 Hibernate 最新版本

java - 为什么 ArrayList<ArrayList<?>> list = new ArrayList<ArrayList<String>>() 无法编译?

database - 使用整数列在数据库中存储美国邮政编码是个好主意吗?

scala - 如何通过scala中类型参数的类型成员来约束参数?

java - JDBC 和 MySQL : Do changes in the underlying database are known to the java program?

java - 是否可以使泛型方法签名实现泛型+接口(interface)?

java - Java中限制泛型二叉搜索树的类型参数的混淆解释

java - 引用与现有类型同名的类