简单说明,就是为了编译的时候使用,javac来使用,生成的class文件里面不会存在泛型。
简单的自定义泛型接口、泛型类和泛型方法
class ZL<T> { //泛型类
12
13 private T obj;
14
15 public ZL() {
16
17 }
18
19 public ZL(T obj) {//泛型参数
20 this.obj= obj;
21 }
22
23 public T getObj() {泛型方法
24 return obj;
25 }
26
27 }
public interface GenericInterface<E> {//泛型接口
public abstract E print(E e);
}
- 1
- 2
- 3
public class GenericClass<T> implements GenericInterface<T>{
@Override
public T print(T t) {
System.out.println(t.getClass());
return t;
}
}
子类使用泛型(泛型的继承)
1)定义
class Student<T> extends Person<T> {//子类继续使用泛型
}
class Student2 extends Person<String> {//子类不再使用泛型
//子类确定类型为String,所以前面也就不需要加<T>,同时对应父类的类型也已被确定
}
2)调用
Student<Integer> s = new Student<Integer>();//创建子类对象,传入类型
s.setAge(10);//调用父类的方法
printInfo(s);//向上转换
Student2 s2 = new Student2();//已经确定类型,不需传入
s2.setAge("11 years");//对应父类的类型已被确定,调用父类方法直接传入String
printInfo(s2);
4.接口使用泛型(接口:特殊的父类)
interface Person<T> {
public void setAge(T age);
public T getAge();
}
class Student<T> implements Person<T> {//子类继续使用泛型
T age;
public void setAge(T age){
this.age = age;
}
public T getAge() {
return this.age;
}
}
class Student2 implements Person<String> {//指定对应接口的泛型类型
String age;///已经确定了类型,直接使用
public void setAge(String age){
this.age = age;
}
public String getAge() {
return this.age;
}
}
public static void main(String args[]) {
Student<Integer> s = new Student<Integer>();//创建子类对象,传入类型
s.setAge(10);
printInfo(s);//向上转换(接口:特殊的父类),子类里实现了方法,同时父类也就是接口没有实现对应的方法,所以里面调用的是子类的方法
Student2 s2 = new Student2();//已经确定类型,不需传入
s2.setAge("11 years");
printInfo(s2);
}
public static void printInfo(Person<?> p) {
System.out.println(p.getAge());
}
类型通配符
1、类型通配符一般是使用?代替具体的类型参数。例如 List<?> 在逻辑上是List<String>,List<Integer> 等所有List<具体类型实参>的父类。
2、类型通配符上限通过形如List<? extends Number>来定义,如此定义就是通配符泛型值接受Number及其下层子类类型。
3、类型通配符下限通过形如 List<? super Number>来定义,表示类型只能接受Number及其三层父类类型,如Objec类型的实例。
实例
public class MaximumTest { // 比较三个值并返回最大值
public static <T extends Comparable<T>> T maximum(T x, T y, T z) { T max = x; // 假设x是初始最大值
if ( y.compareTo( max ) > 0 )
{ max = y; //y 更大 }
if ( z.compareTo( max ) > 0 )
{ max = z; // 现在 z 更大
} return max; // 返回最大对象
}
public static void main(String args[]) {
System.out.printf("%d, %d 和 %d 中最大的数为 %d\n\n", 3, 4, 5, maximum(3, 4, 5));
System.out.printf("%.1f, %.1f 和 %.1f 中最大的数为 %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7));
System.out.printf("%s, %s 和 %s 中最大的数为 %s\n", "pear", "apple", "orange", maximum("pear", "apple", "orange"));
}
}