泛型
泛型类
泛型方法
- 泛型方法并不一定依赖泛型类 没有泛型类泛型方法也是可以执行的
- 泛型方法可以定义在普通类中 也可以定义在泛型类中
public class Arr {
public static void main(String[] args) {
//
String test = C1.test("123");
System.out.println(test);
String test1 = C2.test("123");
System.out.println(test1);
}
}
//泛型方法和泛型类没有关系
class C1<T> {
public static <T> T test(T t) {
System.out.println(t.getClass());
return t;
}
}
//没有泛型 也可以用泛型方法
class C2 {
public static <T> T test(T t) {
System.out.println(t.getClass());
return t;
}
}
泛型的上限和下限
下界只能用在通配符那里 上届可以定义在泛型类和泛型方法中
- 上限
上界两种用法
public class Score<T extends Number> { //设定类型参数上界,必须是Number或是Number的子类
public T getValue() {
return value;
}
}
public static void main(String[] args) {
Score<? extends Number> score = new Score<>("数据结构与算法基础", "EP074512", 10);
}
- 下限
下界只能这么写
public static void main(String[]args){
Score<? super Number>score=new Score<>("数据结构与算法基础","EP074512",10);
Object o=score.getValue();
}