java 泛型类的继承关系和转型问题
两个问题
问题一:FatherClass和ChildClass是父子类的关系,那List
问题二:倘若不是父子类关系,那么通过什么方式可以达到向上转型的效果?
有两个类Fruit和Apple,Apple继承自Fruit,所以Fruit使Apple的父类,关系如下图所示
示例代码
public class GenericMain { public static void method1(Fruit fruit) { System.out.println("lingyejun eat fruit"); } public static void method2(ListfruitList) { System.out.println("lingyejun eat fruit list"); } public static void method3(Collection fruitList) { System.out.println("lingyejun eat fruit collection"); } public static void method4(List<? extends Fruit> fruitList) { System.out.println("lingyejun eat extends fruit list"); } public static void main(String[] args) { method1(new Fruit()); method1(new Apple()); List fruitList = new ArrayList<>(); fruitList.add(new Fruit()); method2(fruitList); List appleList = new ArrayList<>(); appleList.add(new Apple()); method2(appleList);// Compile Error method3(fruitList);// 可以向Collection 中传入List SetfruitSet = new HashSet<>(); method3(fruitSet);// 也可以向Collection 中传入Set method4(fruitList); method4(appleList); } }
method1的方法参数是Fruit类型,想method1方法中传递Fruit类型的变量或者Apple类型的变量都是可以的,因为Apple继承自Fruit,会进行向上类型转换。
method2的方法参数时List
集合类的继承关系
对于泛化的集合类型他们的继承关系,以Collection
同理,我们如果定义一个method3的参数列表为Collection
如果有这样的需求List
可以使用extends关键字来限制泛型参数的适用范围,List
小结
泛型类和普通类一样,可以扩展或实现其他的泛型类或接口。ArrayList
如果我们要实现List
本篇文章如有帮助到您,请给「翎野君」点个赞,感谢您的支持。