Does anyone know why the following code does not compile? Neither add() nor addAll() works as expected. Removing the \"? extends\" part makes everything work, but then I wou
Let me try to explain in what case you might need to use extend Classname>
.
So, lets say you have 2 classes:
class Grand {
private String name;
public Grand(String name) {
this.setName(name);
}
public Grand() {
}
public void setName(String name) {
this.name = name;
}
}
class Dad extends Grand {
public Dad(String name) {
this.setName(name);
}
public Dad() {
}
}
And lets say you have 2 collections, each contains some Grands and some Dads:
List dads = new ArrayList<>();
dads.add(new Dad("Dad 1"));
dads.add(new Dad("Dad 2"));
dads.add(new Dad("Dad 3"));
List grands = new ArrayList<>();
dads.add(new Dad("Grandpa 1"));
dads.add(new Dad("Grandpa 2"));
dads.add(new Dad("Grandpa 3"));
Now, lets asume that we want to have collection, which will contain Grand or Dad objects:
List resultList;
resultList = dads; // Error - Incompatable types List List
resultList = grands;//Works fine
How we can avoid this? Simply use wildcard:
List extends Grand> resultList;
resultList = dads; // Works fine
resultList = grands;//Works fine
Notice, that you cant add new items in such (resultList) collection. For more information you can read about Wildcard and PECS conseption in Java