Solution to 876b: Generics and subclasses
See code at solutions/code/tutorialquestions/question876b
To see that Set<B> cannot safely be a subclass of Set<A>, consider the following method:
public static void addToSet(Set<A> setOfA, A element) {
setOfA.add(element);
}
If Set<B> was subclass of Set<A> then it should be fine to pass a reference of type
Set<B> as the first argument of addToSet. This would mean that the following code would compile without errors:
Set<B> mySetOfB = new HashSet<B>();
A myA = new A();
addToSet(mySetOfB, myA);
But this code would clearly go wrong at runtime: the effect would be an attempt to add myA to mySetOfB, when
mySetOfB is not capable of storing elements of type myA.
You can make the code fragment given in the question compile by changing:
Set<A> setOfA = setOfB;
to either:
Set<?> setOfA = setOfB;
(using a wildcard ?), or:
Set<? extends A> setOfA = setOfB;
(using a bounded wildcard ? extends A).
In the question you were asked for the most specific possible choice, which is the use of the bounded wildcard.