This code:
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) { }
}
Gives such compilation error:
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
From what I understand, E
becomes ? extends Base
, something that extends Base
. So, why new Base()
can't be passed?
Base<? extends Base> compound
means that compound
is parameterized with some subtype of Base
, but you don't know which one. If the parameter type is unknown, then the compiler can't check that new Base()
matches that type.
E
does become ? extends Base
You might think that the method would accept any subtype of Base
, but it doesn't. It only accepts one specific but unknown subtype of Base
.
So you can't call any method that takes E
as a parameter, but you can call a method that returns E
.
Allowing your example to compile would lead to type-safety errors like:
List<? extends Object> list = new ArrayList<String>();
list.add(new Object()); // Error - Can't add object to list of Strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With