复合情况
数组协变,泛型不变
public static void testArrayAndList(){
// B[] r1 = test(new ArrayList<B>()); 编译错误,实参形参类型不匹配
// A[] r2 = test(new ArrayList<B>()); 编译错误,实参形参类型不匹配
// Object[] r3 = test(new ArrayList<Object>()); 编译错误,ArrayList<Object>和ArrayList<A>无任何关系,尽管A继承于Object
A[] r4 = test(new ArrayList<A>());
Object[] r5 = test(new ArrayList<A>());
}
public static A[] test(ArrayList<A> list){
return new A[1];
}
JDK 1.5+重写的方法,参数要求一样,返回值是协变的
public class Diff {
public static void main(String[] args) {
Father foo = new Son();
foo.f1(new B());
}
}
class Father{
public B f1(B obj){
System.out.println("Father.f1()");
return new B();
}
}
class Son extends Father{
@Override
public B f1(B obj) {
System.out.println("Son.f1()");
return new C();//父类返回值的子类,协变
}
}
ArrayList<? extends A> list3 = new ArrayList<B>();//协变
ArrayList<? super B> list4 = new ArrayList<A>();//逆变