<? extends T>和<? super T>

public class Plate<T> {
private T item;

public T getItem() {
return item;
}

public void setItem(T item) {
this.item = item;
}

public Plate(T t){
this.item = t;
}

//内部类-水果,java语法糖,编译的时候也会拆分出来
class Fruit{

}

//内部类-苹果继承自水果
class Apple extends Fruit{

}

@Test
public void test(){
//报错原因:苹果是水果,但装苹果的盘子不是装水果的盘子,就是说,容器里面的东西可以具有继承的关系,但容器之间没有继承的关系
//Plate<Fruit> plate = new Plate<Apple>(new Apple());
//<? extends Fruit>:能放一切水果的盘子,Plate<? extends Fruit>是Plate<Fruit>以及Plate<Apple>的基类
Plate<? extends Fruit> plate = new Plate<Apple>(new Apple());
//上界<? extends T>不能往里存,只能往外取
//1.不能存入任何元素
//plate.setItem(new Apple());
//plate.setItem(new Fruit());

//2.读取元素
//Apple apple = plate.getItem();//Error
Fruit fruit = plate.getItem();
Object object = plate.getItem();

Plate<? super Fruit> plate1 = new Plate<Fruit>(new Apple());
//上界<? super T>不能往外取,只能往里存
//1.读取出来的东西只能放在他的超类Object中
//Apple apple = plate1.getItem();//Error
//Fruit fruit1 = plate1.getItem();//Error
Object object1 = plate1.getItem();

//2.存入元素正常
plate1.setItem(new Apple());
plate1.setItem(new Fruit());

/*PECS原则
最后看一下什么是PECS(Producer Extends Consumer Super)原则,已经很好理解了:
频繁往外读取内容的,适合用上界Extends。
经常往里插入的,适合用下界Super。*/
}
}

猜你喜欢

转载自www.cnblogs.com/anjunshuang/p/9340660.html