我一直在用 Java 测试父类(super class)型泛型,但遇到了障碍。这是我正在测试的示例代码:
import java.util.*;
class GenericTests {
public static void main( String[] args ) {
List<B> list3 = new ArrayList<B>();
testMethod( list3 );
}
public static void testMethod( List<? super B> list ) {
list.add( new A() );
list.add( new B() );
}
}
class A { }
class B extends A { }
编译时报错:
GenericTests.java:20: error: no suitable method found for add(A)
list.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 conve
rsion)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: B from capture of ? super B
1 error
我认为给定 B 的下界,您可以添加任何父类(super class)型?或者这是否仅适用于引用(即方法签名中的参数),因为允许父类(super class)型会破坏类型检查?
最佳答案
声明List<? super B> list
说list
是 List
B 继承的某种类型的对象。但是这种类型不需要与 A
兼容。 .假设层次结构是:
public class A {...}
public class C extends A {...}
public class B extends C {...}
然后,list
可能是 List<C>
.但是然后 list.add(new A())
是非法的。 A
的实例不是 C
的实例.编译器只知道 B
的实例或者可以将子类添加到 list
.
关于java - Java 中的父类(super class)型泛型是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16661503/