public class Test{
public static void main(String[] args){
testPairEmployee(new Pair<>(new Manager(),new Manager()));
}
public static void testPairEmployee(Pair<Employee> p) throws NoSuchMethodException {
p.testFunc();
}
}
class Employee{}
class Manager extends Employee{}
class Pair<T>{
private T first;
private T second;
public Pair(T first, T second){
this.first = first;
this.second = second;
}
public void testFunc() {
System.out.println(first.getClass().getName() + '\t' + second.getClass().getName());
}
}
new Pair<>(new Manager(),new Manager())
的类型是Pair<Manager>
,为什么这段代码能成功运行?
如果您认为它的类型是Pair<Employee>
,但当我编写这段代码时:
testPairEmployee((Pair<Employee>)new Pair<>(new Manager(),new Manager()));
我遇到编译错误:
不可转换的类型;不能强制转换 ‘TestGeneration.Pair<;TestGeneration.Manager>;’至 ‘TestGeneration.Pair<;TestGeneration.Employee>;
换句话说,编译器清楚地知道它的类型是Pair<Manager>
.
为什么?
This part below is due to my unclear presentation. This is actually another question, and I understand why the following code snippet is wrong: because generics are not covariable. Thanks to the two friends who originally posted the answer, I'm sorry for causing you misunderstanding. Friends who see this problem later can ignore this part below.个
同样令我惊讶的是,以下代码运行得很好:
Pair<Employee> p2 = new Pair<>(new Manager(), new Manager());
但下面的代码是ERROR:
Pair<Employee> p3 = new Pair<>(new Employee(), new Employee());
Pair<Manager> p4 = new Pair<>(new Manager(), new Manager());
p3 = p4; // ERROR