Just when I thought I finally understood generics, I came across the following example:
public class Organic {
void react(E e) { }
The topic question is also discussed in several other places like:
It is actually an question from the book for the Java certificate preparation, from the last test (Question 34). The preparation book is based on the lessons book.
Even with the explanation here and under the other links and the writing in the book the solution was not clear for me because the explanations are mostly based on the List interface and reading that I thought it is some inner collection specific soluton.
But if you see the definition of the List interface and the add-method on one side and the the Organic class with its react-method on other side you will notice that they are defined in the similar way.
public interface List extends Collection {
...
boolean add(E e);
...
}
public class Organic {
...
void react(E e) { }
...
}
So all explanation based on the List interface examples which you can find anywhere are valid for this question too.
List extends String> list1 = new ArrayList();
List super String> list2 = new ArrayList();
list1.add(new String()); //The method add(capture#1-of ? extends String) in the type List is not applicable for the arguments (String) - // compile-time error
list2.add(new Object()); //The method add(capture#2-of ? super String) in the type List is not applicable for the arguments (Object) - // compile-time error
Take a look at the explanation on this one: