以下のコードについて質問があります。
コンパイラが 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());
}
}