文章目录
1.协变
当A≤B时有f(A)≤f(B)成立,那么f(⋅)是协变(covariant)的
简单来说,如果A能转型成B,如果与A相关类型也能转型为B类相关类型,那么我们称这种相关类型满足协变
举例:
Apple a = new Apple();
Fruit t = a;
Apple[] apples = new Apple[10];
Fruit[] fruits = apples;
//Apple[] 和Fruit[]满足协变
2.泛型是不满足协变的
例如:class A extends B; 但是List<A>不是List<B>的父类,也就是List<B>不能转型为List<A>,这就带来一个问题,如果List<A>和List<B>的子类存在很多相似代码,那就会代码冗余,如下面printBananas()和printApple()。
static class Food{
private String name;
Food(String name){
this.name = name;
}
public String getName(){
return name;
}
}
static class Fruit extends Food {
Fruit(String name) {
super(name);
}
}
static class Apple extends Fruit{