Consider the following classes:
A.java
public class A {
}
B.java
public class B extends A {
}
Demo.java
import java.util.HashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Set<B> setOfB = new HashSet<B>();
Set<A> setOfA = setOfB;
}
}
The last assignment produces a compilation error. At first sight, this might seem odd: B
is a subclass of A
so, intuitively, Set<B>
should be a subclass of Set<A>
and the assignment should be correct by virtue of polymorphism. This, however, is not the case:
Set<B>
is not a subclass of Set<A>
. Explain why this is not the case.
Adjust the last statement, changing the generic parameter A
of Set<A>
to something more relaxed. There are two choices
here; you should pick the most specific possible choice. You may find that the Java Generics
tutorial helps in figuring this out (and it is highly recommended that you
read this tutorial anyway).
Hint: Assume for the moment that Set<B>
is a subclass of Set<A>
and that the mentioned assignment is correct.
Consider now the following operation:
setOfA.add(new A());
This operation is syntactically correct, but can you see the problem that it would cause in our example?