Why can't the new Base () be passed to <? expands base>?

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 a compilation error like this:

 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 getting ? extends Base ? extends Base , which extends Base . So why can't new Base() be passed?

+5
source share
2 answers

Base<? extends Base> compound Base<? extends Base> compound means that compound parameterized by some subtype of Base , but you don’t know which one. If the type of the parameter is unknown, the compiler cannot check whether new Base() matches this type.

E getting ? extends Base ? extends Base You might think that the method will accept any subtype of Base , but it is not. It accepts only one specific but unknown subtype of Base .

That way, you cannot call any method that takes E as a parameter, but you can call a method that returns E

Providing your compilation example will lead to security errors like, for example:

 List<? extends Object> list = new ArrayList<String>(); list.add(new Object()); // Error - Can't add object to list of Strings. 
+7
source

Try the following to define your method as generic:

 <E> void method(E e) { } 

Note the addition of <E> .

This fixed a compilation error for me. Although, I would expect that the parameter you provided at the class level should have been applied.

0
source

Source: https://habr.com/ru/post/1208951/


All Articles