//1 泛型方法的定义和使用
public static void main(String[] args)throws ClassNotFoundException{
String str = get("哈士奇","world");
System.out.println(str);//输出打印 哈士奇
}
// static <T,U>T 是指定返回状态值 t
public static <T,U>T get(T t,U u){
if (u !=null){
return t;
}else {
return null;
}
}
// 2 泛型接口的定义和使用
public static void main(String[] args)throws ClassNotFoundException{
ShoeText showTest = new ShoeText();
showTest.show("哈士奇",new Date());//Date() 系统时间
}
static class ShoeText implements Show<String, Date>{
@Override
public void show(String str, Date date) {
System.out.println(str);//打印输出 哈士奇
System.out.println(date);//打印输出 Tue Feb 02 10:38:47 CST 2021
}
}
interface Show<T,U> {
void show(T t ,U u);
}
// 3 泛型变量的类型限定
类型限定就是使用extends关键字对类型变量加以约束。比如限定泛型参数只接受Number类或者子类Integer、Float等,可以这样限定<T extends Number>,这样限定之后,实际参数只能是Number类或者Number的子类。下面举例详细说明:
//定义一个水果类
//里面有一个示例方法getWeight()可以获取水果重量
public class Fruit {
public int getWeight() {
return 10; //这里假设所有水果重量都是10
}
}
public class Apple extends Fruit {}
//定义泛型类Box,并限定类型参数为Fruit
public class Box<T extends Fruit> {}
//由于Box限定了类型参数,实际类型参数只能是Fruit或者Fruit的子类
Box<Fruit> integerBox = new Box<Fruit>();//编译通过
Box<Apple> integerBox = new Box<Apple>();//编译通过
Box<Integer> integerBox = new Box<Integer>();//编译器报错