I was going through this article to understand the role of super
wildcard in generics. I understood how extends
works, but I am having difficulty understanding super
I have a ClassA
that is extended by ClassB
, making ClassA
super class of ClassB
.
If I understood the article correctly, the <? super ClassB>
would allow any Class that is a super type of ClassB
.
I have the following code
GenericMethod.java
public class GenericMethod<T> {
private List<T> list;
public GenericMethod() {
list = new ArrayList<>();
}
public void add(T t) {
list.add(t);
}
public T get(int index) {
return list.get(index);
}
}
Driver.java
public class Driver {
public static void main(String[] args) {
GenericMethod<? super ClassB> genericMethod = new GenericMethod<>();
ClassA classA = new ClassA();
genericMethod.add(classA); // Compile-time error here
}
}
Error
The method add(capture#1-of ? super ClassB) in the type GenericMethod<capture#1-of ? super ClassB> is not applicable for the arguments (ClassA)
I don't understand where I am going wrong. When I instantiated the GenericMethod
class, I already declared that it would accept any value that is a super type of ClassB
with the declaration <? super ClassB>
. Thus, the T
inside the GenericMethod
class should accept all classes that ClassB
extends.
Why does the add
method throw the compile-time error then? Shouldn't the method add
already know that it's being passed a perfectly compatible type?