zoukankan      html  css  js  c++  java
  • Java泛型通配符

    class Fruit{}
    class Apple extends Fruit{}
    class Plate<T>{
        private T item;
        public Plate(){}
        public Plate(T t){
            item=t;
        }
        public void set(T t){
            item=t;
        }
        public T get(){
            return item;
        }
    }
    public class GenericTest {
        public static void main(String[] args) {
            Fruit a=new Fruit();
            Fruit b=new Apple();
            Plate<Fruit> c=new Plate<Fruit>();
            //Apple是Fruit的子类,但Plate<Apple>不是Plate<Fruit>的子类
            //Plate<Fruit> d=new Plate<Apple>();
    
            //? extends Fruit就代表Fruit或Fruit的子类
            Plate<? extends Fruit> e=new Plate<Apple>();
            Plate<? extends Fruit> f=new Plate<>();
    
            //无法set/add,类型不匹配,编译器不知道具体是在处理哪个子类。
            //e.set(new Fruit());
            //e.set(new Apple());
            Plate<? extends Fruit> g=new Plate<Apple>(new Apple());
            //可以get,可以强制转型为Fruit子类。
            Apple h= (Apple) g.get();
            Fruit i=g.get();
    
            //? super Fruit代表Fruit或Fruit的父类
            Plate<? super Fruit> j=new Plate<>();
            //可以set存入Fruit或Fruit的子类,会被统一成Fruit的某一个父类。
            j.set(new Fruit());
            j.set(new Apple());
            //可以get,但只能返回Object,因为不知道具体是哪个父类
            Object k= j.get();
        }
    }
    
  • 相关阅读:
    找水王
    统计txt文档中的单词个数
    返回一个数组中最大子数组的和
    寻找最长字符串
    第二阶段冲刺第九天
    第二阶段冲刺第八天
    第二阶段冲刺第七天
    第二阶段冲刺第六天
    构建之法阅读笔记06
    小目标
  • 原文地址:https://www.cnblogs.com/zxcoder/p/12253266.html
Copyright © 2011-2022 走看看