interface Info24 { // 在接口上定义泛型
public T getVar(); // 定义抽象方法,抽象方法的返回值就是泛型类型
}
class InfoImp24 implements Info24 { // 定义泛型接口的子类
private T var; // 定义属性
public InfoImp24(T var) { // 通过构造方法设置属性内容
this.setVar(var);
}
public void setVar(T var) {
this.var = var;
}
public T getVar() {
return this.var;
}
}
public class GenericsDemo24 {
public static void main(String arsg[]) {
Info24 i = null; // 声明接口对象
i = new InfoImp24("it"); // 通过子类实例化对象
System.out.println("Length Of String : " + i.getVar().length());
}
}
// Java泛型接口
interface Info25 { // 在接口上定义泛型
public T getVar(); // 定义抽象方法,抽象方法的返回值就是泛型类型
}
class InfoImp25 implements Info25 { // 定义泛型接口的子类
private String var; // 定义属性
public InfoImp25(String var) { // 通过构造方法设置属性内容
this.setVar(var);
}
public void setVar(String var) {
this.var = var;
}
public String getVar() {
return this.var;
}
}
public class GenericsDemo25 {
// 该批注的作用是给编译器一条指令,告诉它对被批注的代码元素内部的某些警告保持静默。
/*
* @description "deprecation" 使用了不赞成使用的类或方法时的警告
*
* @description "unchecked" 执行了未检查的转换时的警告,例如当使用集合时没有用泛型 (Generics)
* 来指定集合保存的类型。
*
* @description "fallthrough" 当 Switch 程序块直接通往下一种情况而没有 Break 时的警告。
*
* @description "path" 在类路径、源文件路径等中有不存在的路径时的警告。
*
* @description "serial" 当在可序列化的类上缺少 serialVersionUID 定义时的警告。
*
* @description "finally" 任何 finally 子句不能正常完成时的警告。
*
* @description "all" 关于以上所有情况的警告。
*/
@SuppressWarnings("unchecked")
public static void main(String arsg[]) {
Info25 i = null; // 声明接口对象
i = new InfoImp25("it"); // 通过子类实例化对象
System.out.println("Length Of String : "
+ i.getVar().toString().length());
}
}