【Java基礎總結】泛型

來源:互聯網
上載者:User

標籤:log   string   tools   out   pl2   interface   使用   eric   str   

泛型實現了參數化型別的概念,使代碼可以應用於多種類型。

1. 泛型類

聲明的泛型型別靜態方法不能使用

class Tools<T>{    private T t;    public void set(T t){        this.t = t;    }    public T get(){        return this.t;    }}
2. 泛型方法
class GenericTest2<T>{    //使用類定義的泛型    public void print1(T t){        System.out.println("print1:"+t);    }    //使用方法定義的泛型    public <E> void print2(E e){        System.out.println("print2:"+e);    }    //靜態方法不能使用類定義的泛型    public static <E> void print3(E e){        System.out.println("print3:"+e);    }}
3. 泛型介面
//泛型介面interface Inter<T>{    void show(T t);}//class InterImpl2 implements Inter<String>{    public void show(String t)    {        System.out.println("show:"+t);    }    }//class InterImpl<T> implements Inter<T>{    public void show(T t){        System.out.println("show:"+t);    }}class GenericDemo5{    public static void main(String[] args){        InterImpl<Integer> i = new InterImpl<Integer>();        i.show(5);        //InterImpl i = new InterImpl();        //i.show("liu");        }}
4. 泛型限定
HashSet<? extends Person> set = new HashSet<? extends Person>();   //限定儲存Person或Person子類的對象HashSet<? super Person> set = new HashSet<? super Person>();   //限定儲存Person或Person父類的對象

 

【Java基礎總結】泛型

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.