这段代码:
public class Base<E> {
static void main(String[] args) {
Base<? extends Base> compound = new Base<Base>();
compound.method(new Base());
} // ^ error
void method(E e) { }
}
Run Code Online (Sandbox Code Playgroud)
给出了这样的编译错误:
Error:(4, 17) java: method method in class Base<E> cannot be applied to given types;
required: capture#1 of ? extends Base
found: Base
reason: actual argument Base cannot be converted to capture#1 of ? extends Base by method invocation conversion
Run Code Online (Sandbox Code Playgroud)
从我的理解,E成为? extends Base,延伸的东西Base.那么,为什么new Base()不能通过呢?
Base<? extends Base> compound表示compound使用某个子类型参数化Base,但您不知道哪一个.如果参数类型未知,则编译器无法检查new Base()该类型是否匹配.
E确实成为? extends Base你可能会认为,该方法将接受任何的亚型Base,但事实并非如此.它只接受一个特定但未知的子类型Base.
所以你不能调用任何E作为参数的方法,但你可以调用一个返回的方法E.
允许您的示例进行编译会导致类型安全错误,例如:
List<? extends Object> list = new ArrayList<String>();
list.add(new Object()); // Error - Can't add object to list of Strings.
Run Code Online (Sandbox Code Playgroud)