標籤: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基礎總結】泛型