我对下面的代码有疑问。
你能告诉我为什么编译器拒绝接受 ty.add(new A()); 吗?毕竟 A 是 B 的超类(即,对应于要求)。
错误信息如下:
C.java:15: error: no suitable method found for add(A)
ty.add(new A());
^
method List.add(int,CAP#1) is not applicable
(actual and formal argument lists differ in length)
method List.add(CAP#1) is not applicable
(actual argument A cannot be converted to CAP#1 by method invocation conversion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: B from capture of ? super B
1 error
这是代码(C.java):
import java.util.ArrayList;
import java.util.List;
class A
{
}
class B extends A
{
}
class C extends B
{
public static void main(String args[])
{
List<? super B> ty = new ArrayList<A>();
ty.add(new A());
ty.add(new B());
ty.add(new C());
}
}