Given a simple class …
public class Parent {
private final String value;
public Parent(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
… and a subclass of it, …
public class Child extends Parent {
public Child(String value) {
super(value);
}
}
… the following program compiles and executes without errors or warnings:
public class Main {
public static void main(String[] args) {
List<? extends Parent> items = getItems();
for (Parent p : items) {
System.out.println(p.toString());
}
}
private static List<? extends Parent> getItems() {
List<Parent> il = new ArrayList<Parent>();
il.add(new Parent("Hello"));
il.add(new Child("World"));
return il;
}
}
But what about the return type of getItems()
? It seems semantically wrong to me, since the result of the function does contain a Parent
object which is not a subclass of Parent
what I would expect from that method signature. Given this behaviour, I would have expected a simple List<Parent>
as return type. However, since the compiler doesn’t complain, do I miss something? Is there any benefit from this implementation, aside from an (unnecessary) “write protection” for the result list? Or is this java style to write-protect result lists (not in this example, but, for example, to expose an object’s field list without needing to create a copy)? Or can this simply be considered “wrong” (in terms of teaching)? If so, why does neither the compiler nor even Eclipse complain about it, not even showing a hint?
Parent
-typed variable. You don't know if theList
is able to storeParent
or onlyChild
why it could be a bad idea to write to it. – DidiParent
IS a subclass ofParent
and 2. The list is not "write protected": You can still addnull
(or remove elements) – Delphinus