泛型接口

在类上自定义泛型,T不能是基本数据类型,如int,需用Integer。

泛型接口:

interface 接口名<声明自定义泛型> {

    ...

}

interface Dao<T> {

  public void add(T t);

}

①,确定类型。

public class Demo implements Dao<String< {

  public void add(String t) {

  }

}

②,未确定类型。

public class Demo<T> implments Dao<T> {

  public void main(String[] args) {

         Demo<String> d = new Demo<String>();

  }

      public void add(T t) {

      }

}

 1 package 泛型接口;
 2 
 3 
 4 interface test<T> {
 5     public void add(T t);
 6 }
 7 
 8 //方式一。未确定类型,延迟接口自定义类型
 9 /*public class Interfacetest<T> implements test<T>{
10 
11     public static void main(String[] args) {
12         
13         Interfacetest<String> tf = new Interfacetest<String>();
14         tf.add("ok");
15     }
16 
17     @Override
18     public void add(T t) {
19         System.out.println("InterfaceTest....." + t);
20         
21     }
22 }*/
23 
24 
25 //方式二。确定 接口自定义类型
26 public class Interfacetest implements test<String> {
27     public static void main(String[] args) {
28         Interfacetest ift = new Interfacetest();
29         ift.add("ok2");
30     }
31     
32     public void add(String t) {
33         System.out.println("add.."+t);
34     }
35 }
 1 package 泛型接口;
 2 
 3 class Tool<T> {
 4     
 5     //1.方式一
 6     public void print(T[] t) {
 7         System.out.println("print..."+ t[1]);
 8     }
 9     
10     //2.方式二。在类上自定义泛型不能作用于静态方法。如果静态方法需要自定义泛型,则要在方法上声明使用
11     public static <T>void method(T[] t) {
12         System.out.println("method.."+t[2]);
13     }
14 }
15 
16 public class MyArray {
17     public static void main(String[] args) {
18         Integer[] arr = {1,2,3};
19         //1.T通过创建对象传递
20         Tool<Integer> tool = new Tool<Integer>();
21         tool.print(arr);
22         
23         //2.T通过参数传递
24         
25     }
26 }
原文地址:https://www.cnblogs.com/linst/p/5655647.html