【发布时间】: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?
}
【问题讨论】:
-
副本解释了为什么不允许使用 1 和 2,并且应该隐含地解释为什么也不允许使用 3。您可能还想查看:Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?.