java-泛形使用

來源:互聯網
上載者:User

標籤:interface   public   method   而且   java   

1.類,方法上的泛形

//泛型類定義的泛型,在整個類中有效。如果被方法使用,//那麼泛型類的對象明確要操作的具體類型後,所有要操作的類型就已經固定了。////為了讓不同方法可以操作不同類型,而且類型還不確定。//那麼可以將泛型定義在方法上。/*特殊之處:靜態方法不可以訪問類上定義的泛型。如果靜態方法操作的應用資料類型不確定,可以將泛型定義在方法上。*/class Demo<T>{public  void show(T t){System.out.println("show:"+t);}public <Q> void print(Q q){System.out.println("print:"+q);}public  static <W> void method(W t){System.out.println("method:"+t);}}

2.介面,實現介面的泛形

/泛型定義在介面上。interface Inter<T>{void show(T t);}/*class InterImpl 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);}}

3.泛形的限定符,萬用字元(注意:?萬用字元只能使用在已經定義了泛形的類上,進行該類上的泛形限定)

/*? 萬用字元。也可以理解為預留位置。泛型的限定;? extends E: 可以接收E類型或者E的子類型。上限。? super E: 可以接收E類型或者E的父類型。下限注意:?萬用字元只能使用在已經定義了泛形的類上,進行該類上的泛形限定*/class  GenericDemo6{ public static void printColl(Collection<? extends Person> al){Iterator<? extends Person> it = al.iterator();while(it.hasNext()){System.out.println(it.next().getName());}} public static void printColl(ArrayList<?> al)//ArrayList al = new ArrayList<Integer>();error{Iterator<?> it = al.iterator();while(it.hasNext()){System.out.println(it.next().toString());}} }class Fu<T>{}class InterImp {public void integer(Fu<? extends Integer> f) {}public void string(Fu<? super String> f){}}  


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.