如果B是A的子类,并且F(B)也是F(A)的子类,那么F即为协变
如果B是A的子类,并且F(B)成了F(A)的父类,那么F即为逆变
Java中的泛型有逆变和协变两种操作,定义如下:
<? extends A>
B是A的子类,那么List< B >是List<? extends A>的子类
<? supper A>
B是A的子类,那么List< B >是List<? super A>的父类
Java的协变逆变及其约束,都是出于对多态的应用。为了后续说明方便,这里先定义一系列的父子类
class Fruit { public String returnMeat() { return "generic fruit meat"; } } class Apple extends Fruit { @Override public String returnMeat() { return "apple meat"; } } class GreenApple extends Apple { @Override public String returnMeat() { return "green apple meat"; } }
Java是支持多态的。如果一个方法的参数接收的是A类型,那么将其子类型作为参数,调用该方法,依然可行。
例如eatFruitMeat方法就能体现多态特性
@Test public void test1() { eatFruitMeat(new Fruit());//输出eat generic fruit meat eatFruitMeat(new Apple());//输出eat apple meat eatFruitMeat(new GreenApple());//输出eat green apple meat } public void eatFruitMeat(Fruit fruit) { System.out.println("eat "+fruit.returnMeat()); }
协变方法支持对传入参数的读操作,但不支持修改操作。如下:
@Test public void test1() { List<GreenApple> greenApples = Lists.newArrayList(new GreenApple()); List<Fruit> fruits = Lists.newArrayList(new Fruit()); List<Apple> apples = Lists.newArrayList(new Apple()); eatFruitMeats(greenApples); eatFruitMeats(fruits);//编译错误1 eatFruitMeats(apples); } public void eatFruitMeats(List<? extends Apple> fruits) { fruits.forEach(fruit->System.out.println("eat "+fruit.returnMeat())); fruits.add(new Apple());//编译错误2 fruits.add(new Fruit());//编译错误3 fruits.add(new Object());//编译错误4 }
逆变主要在写的场景,即只能向逆变容器中添加,下界类型本身或其子类
@Test public void test1() { List<Fruit> fruits = Lists.newArrayList(); List<Apple> apples = Lists.newArrayList(); List<GreenApple> greenAppleLists = Lists.newArrayList(); collectFruits(fruits); collectFruits(apples); collectFruits(greenAppleLists);//编译错误1 } public void collectFruits(List<? super Apple> fruits) { fruits.add(new Fruit());//编译错误2 fruits.add(new Apple()); fruits.add(new GreenApple()); }
Java泛型支持协变和逆变,具体在使用时,会有一些约束。这些约束,需要从Java语言的特性,比如多态性,以及运行时安全性去理解。
简单总结协变、逆变参数的方法调用特点如下:
https://medium.com/@sinisalouc/variance-in-java-and-scala-63af925d21dc