【问题标题】:Java compilation error when using wildcard generics extends [duplicate]使用通配符泛型时的Java编译错误扩展[重复]
【发布时间】:2026-02-18 16:50:01
【问题描述】:

我有一个派生类Father 和一个基类Parent 例如

public static class Parent {
}
public static class Father extends Parent {
}

我想知道为什么不允许以下内容?

public static List<Parent> foo() {
    List<? extends Parent> list = new ArrayList<>();
    list.add(new Parent());  // 1. why is this not allowed?
    list.add(new Father());  // 2. why is this not allowed?
    return list;  // 3. why is this not allowed?
}

【问题讨论】:

标签: java generics


【解决方案1】:

你可以试试下面的代码->

 public static List<Parent> foo() {
        List<Parent> list = new ArrayList<>();
        list.add(new Parent());  // 1. why is this not allowed?
        list.add(new Father());  // 2. why is this not allowed?
        return list;  // 3. why is this not allowed?
    }

【讨论】:

    【解决方案2】:

    ? extends Parent 用作泛型参数意味着它表示一个扩展Parent 的类,因此不是Parent 本身。要包含Parent 本身,只需使用Parent 作为通用参数(即List&lt;Parent&gt;)。

    【讨论】: