class Fruit {
    public int add(){
        return 0;
    }
}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}

class CovariantArrays {
    public static void main(String[] args) {
        //上界
        List<? extends Fruit> flistTop = new ArrayList<Apple>();
        flistTop.add(null);
        // flistTop.get(0).add();
        //add Fruit对象会报错
        //flist.add(new Fruit());
        Fruit fruit1 = flistTop.get(0);

        //下界
        List<? super Apple> flistBottem = new ArrayList<>();
        flistBottem.add(new Apple());
        flistBottem.add(new Jonathan());
        flistBottem.forEach(a -> {
            if (a instanceof Jonathan) {
                System.out.println("a instanceof Jonathan"); //正确输入
            }
        });
        //get Apple对象会报错
        //Apple apple = flistBottem.get(0);
    }
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。