I am struggling with Java 8 wildcard generics.
Assume a generic class (from Core Java book) called Pair<T>
class Pair<T> {
private T first;
private T second;
public Pair() {
first = null;
second = null;
}
public Pair(T first, T second) {
this.first = first;
this.second = second;
}
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
Assume the following class hierarchy:
base Employee (top of hierarchy), then
Manager extends Employee, and then
Executive extends Manager
The following code below works but I don't understand why it is allowed.
Pair<? super Manager> pm2 =
new Pair<>(
new Employee(1,"Yuri"), // Employee is super of Manager
new Executive()); // Executive is not super of Manager
// why Executive is allowed in above Pair<T> ?
Employee ex1 = (Employee) pm2.getFirst(); // OK
Manager ex2 = (Manager) pm2.getSecond(); // OK
Executive ex3 = (Executive) pm2.getSecond(); // why is allowed?
I dont understand why Executive works above given it is not a super-type but it is a sub-type of Manager.
Is it because Java 8 compiler converts ? super Manager to Object and therefore anything will be permitted?