我希望有一个列表,其中包含父类(例如“ Parent”)或其子类“ Child”中的任何一个的实例,但它们似乎都不起作用。我不明白编译器到底在抱怨什么,以及它不允许在其中添加项目的原因是什么。
import java.util.List;
import java.util.ArrayList;
class Parent {
}
class Child extends Parent {
}
class Hello {
public static void main(String args[]) {
List<? extends Parent> parents = new ArrayList<Child>();
parents.add(new Child());
}
}
// Compile time error
Hello.java:17: error: no suitable method found for add(Child)
parents.add(new Child());
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; Child cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; Child cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Parent from capture of ? extends Parent
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
例外