泛型类
package com.woniuxy.senior;
/*
* 泛型类
*/
public class GenericClass<T> {
T t;
// 泛型构造方法
public GenericClass() {
}
public GenericClass(T t) {
this.t = t;
}
// 封装
public T getT() {
return this.t;
}
public void setT(T t) {
this.t = t;
}
// 使用泛型类
public static void main(String[] args) {
// 实例化 泛型类,指定实际类型,所有的 T 都会替换成 Interger
GenericClass<Integer> g = new GenericClass<Integer>(2);
// 使用
System.out.println(g.getT());
}
}
泛型接口
package com.woniuxy.senior;
// 定义泛型接口
public interface GenericInterface<T> {
// 定义泛型抽象方法
public abstract T print(T t);
// 不能使用泛型类型定义 接口属性,这样会报错
// public static final T tt;
// 这样可以
public static final double PI = 3.14;
}
实现泛型接口
package com.woniuxy.senior;
// 实现泛型接口
public class GInterImp<T> implements GenericInterface<T> {
// 实现泛型接口 抽象方法
@Override
public T print(T t) {
System.out.println(t);
return t;
}
}