Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why new Base() cannot be passed to <? extends Base>?

Tags:

java

generics

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?

like image 306
Adam Stelmaszczyk Avatar asked Dec 13 '14 14:12

Adam Stelmaszczyk


Video Answer


1 Answers

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.
like image 152
fgb Avatar answered Nov 15 '22 05:11

fgb