標籤: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-泛形使用