目录
一、泛型方法
1.泛型方法的好处:
不用再写很多不同数据类型的方法再去调用了,直接写一个泛型方法进行调用,想用什么数据类型就用什么数据类型。
2.泛型方法的格式:
- 格式:修饰符<类型> 返回值类型 方法名(类型 变量名){}
- 示例:public <T> void show(T t){}
代码示例:
/*自定义泛型类的使用:泛型方法*/
public class GenericDemo_02 {
public static void main(String[] args) {
//方法一:自己写好方法,再进行调用
/* Generic g = new Generic();
g.show("张三");
g.show(20);
g.show(true);*/
//方法二:使用泛型类改进
/* Generic<String> g1 = new Generic<>();
g1.show("张三");
Generic<Integer> g2 = new Generic<>();
g2.show(20);
Generic<Boolean> g3 = new Generic<>();
g3.show(true);*/
//方法三:使用泛型方法:
Generic g = new Generic();
g.show("张三");
g.show(20);
g.show(true);
}
}
package myGeneric_Demo02;
/*
//方法一:自己写好方法之后,再进行方法调用
public class Generic {
public void show(String s) {
System.out.println(s);
}
public void show(Integer i) {
System.out.println(i);
}
public void show(Boolean b) {
System.out.println(b);
}
}
*/
//方法二:使用泛型类改进
/*public class Generic<T> {
public void show(T t) {
System.out.println(t);
}
}*/
//方法三:泛型方法改进
public class Generic {
public <T> void show(T t) {
System.out.println(t);
}
}
二、泛型接口
1.泛型接口的格式:
- 格式:修饰符 interface 接口名<类型>{}
- 范例:public interface Generic<T>{}
代码示例:
/*泛型接口的定义*/
package myGeneric_Demo03;
public interface Generic<T> {
void show(T t);
}
package myGeneric_Demo03;
/*泛型接口的实现类*/
public class GenericImpl<T> implements Generic<T> {
@Override
public void show(T t) {
System.out.println(t);
}
}
package myGeneric_Demo03;
/*泛型接口的使用*/
public class GenericInterface {
public static void main(String[] args) {
Generic<String> g1 = new GenericImpl<>();
g1.show("张三");
Generic<Integer> g2 = new GenericImpl<>();
g2.show(20);
Generic<Boolean> g3 = new GenericImpl<>();
g3.show(true);
}
}