15.10 通配符

  • fruit的动态类型是Apple[],不是Fruit[]也不是Orange[];
  • fruit虽然只能放Apple或Apple的子类型,但编译期可以放Fruit和Fruit的子类型;
  • 这里不是向上转型,而是将一个数组赋值给另一个数组;
package chapter15._10;

class Fruit{}
class Apple extends Fruit{}
class Jonathan extends Apple{}
class Orange extends Fruit{}

public class CovariantArrays {

    public static void main(String[] args) {
        Fruit[] fruit = new Apple[10];
        fruit[0] = new Apple();
        fruit[1] = new Jonathan();

        // Runtime is Apple[], not Fruit[] or Orange[]
        try {
            fruit[0] = new Fruit();
        } catch (Exception e) {
            System.out.println(e);
        }

        try {
            fruit[0] = new Orange();
        } catch (Exception e) {
            System.out.println(e);
        }
    }

}
  • 不能把一个涉及Apple的泛型赋给一个涉及Fruit的泛型;
  • 这不是向上转型,Apple的List不是Fruit的List;
package chapter15._10;

import java.util.ArrayList;
import java.util.List;

public class NonCovariantGenerics {

//    List<Fruit> flist = new ArrayList<Apple>();

}
  • 这么干,fList中将不能添加任何对象;
  • List中add(E e)的参数是有泛型的,当集合声明成List<? extends Fruit> fList时,add(E e)将变成add(? extends Fruit e),List中参数有通配符的方法是不能被调用的,因此add()无法被调用;
package chapter15._10;

import java.util.ArrayList;
import java.util.List;

public class GenericsAndCovariance {

    public static void main(String[] args) {
        List<? extends Fruit> fList = new ArrayList<Apple>();
//        fList.add(new Apple());
//        fList.add(new Fruit());
//        fList.add(new Object());
        fList.add(null);
        Fruit f = fList.get(0);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值