I don't understand why/when we should use Upper-Bounded Wildcards since you can not use it. Here is an example :
import java.util.ArrayList;
import java.util.List;
public class Test {
static class Parent { }
static class Child extends Parent { }
public static void main(String[] args) {
List<? extends Parent> family = new ArrayList<>();
family.add(new Child()); // 1. Doesn't compile
family.add(new Parent()); // 2. Doesn't compile
// List<Parent> parents = new ArrayList<>();
// List<Child> childs = new ArrayList<>();
// parents.add(new Child()); // 3. Compile fine
// childs.add(new Parent()); // 4. Doesn't compile
}
}
The point 1 and 2 doesn't compile. From what I have understood this will not compile because List<? extends Parent>
can be List<Parent>
or List<Child>
, and since you can not for instance add a Parent instance in a List, Java prevent us of doing this and gives a compilation error. So my question is what's the point in using Upper-Bounded Wildcards??