Set<? extends AbstractGroup> test;
This means your set can be a set of any object that extends AbstractGroup
, but normally the compiler would not allow you to add something to that set (since it can't tell whether you'd for example add a SubGroupB
to a Set<SubGroupA>
etc.).
test = new HashSet<SubGroupA>()
Your actual set would only contain objects of type SubGroupA
and subclasses thereof.
However, the compiler would still not know what the content of test
would be (see above).
The point of the wild card is: you can assign any set to the variable that is parameterized with AbstractGroup
or a subclass, thus assuring you can cast all objects already in that map to AbstractGroup
(which the compiler checks for).
If you want to have a set that can contain any AbstractGroup
object, just don't use the wildcard.
//this would compile (under the assumption that SubGroupA extends AbstractGroup)
Set<? extends AbstractGroup> test = new HashSet<SubGroupA>();
//this wouldn't compile, since the compiler doesn't know the type of test (it might change at runtime etc.)
test.add(new SubGroupA());
//this wouldn't compile since AbstractGroup and SubGroupA are not the exact same type (hence the wildcard would be needed here)
Set<AbstractGroup> test = new HashSet<SubGroupA>();
//this would compile
Set<AbstractGroup> test = new HashSet<AbstractGroup>();
test.add(new SubGroupA());