我正在努力使用 Java 8 通配符泛型。
假设一个泛型类(来自 Core Java 书籍)称为 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; }
}
假设有以下类层次结构:
base Employee(层次结构的顶部),然后
Manager扩展Employee,然后
Executive扩展Manager
下面的代码有效,但我不明白为什么允许它。
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?
我不明白为什么 Executive 在上面工作,因为它不是超级类型,而是经理的子类型。
是因为 Java 8 编译器会转换吗?超级店长到对象,所以任何事情都会被允许?
MMTTMM
相关分类