泛型简介
将类型作为参数传递
泛型必须是应用类型
常见形式有:泛型类 泛型接口 泛型方法
泛型好处:提高代码的重用性 防止类型转换异常 提高代码的安全性
泛型类
public class Generic_Class<T> {
T t;
public void show(T t){
System.out.println(t);
}
public T getT(){
return t;
}
}
Generic_Class<String> geclass = new Generic_Class<>();
geclass.t = "泛型参数";
geclass.show("输出泛型参数");
System.out.println(geclass.getT());
Generic_Class<Integer> geclass2 = new Generic_Class<>();
geclass2.t = 12;
geclass2.show(13);
System.out.println(geclass2.getT());
泛型接口
public interface Generic_Interface<T> {
String name = "zyt";
T server(T t);
}
public class My_Generic_Interface<T> implements Generic_Interface<T>{
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
My_Generic_Interface impl = new My_Generic_Interface();
My_Generic_Interface<String> impl2 = new My_Generic_Interface<>();
impl.server("zyt");
impl.server(12);
impl2.server("zyt");
泛型方法
public class Generic_Method {
public <T> T show(T t){
System.out.println("泛型方法" + t);
return t;
}
}
Generic_Method methods = new Generic_Method();
methods.show("zyt");