您的位置:首页 > 其它

泛型接口

2016-07-09 13:00 369 查看
在类上自定义泛型,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) {

}

}

package 泛型接口;

interface test<T> {
public void add(T t);
}

//方式一。未确定类型,延迟接口自定义类型
/*public class Interfacetest<T> implements test<T>{

public static void main(String[] args) {

Interfacetest<String> tf = new Interfacetest<String>();
tf.add("ok");
}

@Override
public void add(T t) {
System.out.println("InterfaceTest....." + t);

}
}*/

//方式二。确定 接口自定义类型
public class Interfacetest implements test<String> {
public static void main(String[] args) {
Interfacetest ift = new Interfacetest();
ift.add("ok2");
}

public void add(String t) {
System.out.println("add.."+t);
}
}


package 泛型接口;

class Tool<T> {

//1.方式一
public void print(T[] t) {
System.out.println("print..."+ t[1]);
}

//2.方式二。在类上自定义泛型不能作用于静态方法。如果静态方法需要自定义泛型,则要在方法上声明使用
public static <T>void method(T[] t) {
System.out.println("method.."+t[2]);
}
}

public class MyArray {
public static void main(String[] args) {
Integer[] arr = {1,2,3};
//1.T通过创建对象传递
Tool<Integer> tool = new Tool<Integer>();
tool.print(arr);

//2.T通过参数传递

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: