The following assignment is legal, provided Clerk
is an Employees
[sic].
Pair<? extends Employees> employees = new Pair<Clerk>(clerk1, clerk2);
You shouldn't be able to call setFirst
and pass a Manager
, because here, it's really Pair<Clerk>
.
This illustrates why Java doesn't allow calling a method with the generic type parameter in it (T
) if there is a ? extends
wildcard. The compiler doesn't know which class it really is - Employee
? A subclass? Which subclass? Due to type erasure, the JVM can't check for type safety, so the compiler must disallow all such calls with everything except null
, which can be cast to any reference type and is always allowed.
With ? super Employee
, the lower bound is Employee
. It could be Pair<Object>
. But, passing an Employee
or one of its subclasses is safe, because they are subclasses of anything allowed by ? super Employee
.