1.子类的泛型类型要和父类的泛型类型一致 class GenericChild1.2 方式二 :子类不是泛型类extends GenericFather 2.子类的泛型类型要包含父类的泛型类型 class GenericChild extends GenericFather
在实现继承时,必须要明确指定父类的泛型类型 class GenericChild2.实现一下泛型类的继承 2.1 定义一个泛型父类extends GenericFather
public class GenericFather2.2 定义一个继承了父类的泛型子类{ protected T t; // 一个泛型的属性 //构造方法 public GenericFather() { } public GenericFather(T t) { this.t = t; } // getter/setter 方法 public T getT() { return t; } public void setT(T t) { this.t = t; } //自己写一个和泛型相关的普通方法 public void sayHello(T t,String name){ System.out.println("Hello "+name+";This is father T : "+t); } //toString 方法 @Override public String toString() { return "GenericFather{" + "t=" + t + '}'; } }
public class GenericChild2.3 定义一个继承了父类的普通子类extends GenericFather { private String name; // 声明一个自己的属性 private E e; // 一个特有的泛型类型的属性 // 构造方法 public GenericChild() { } public GenericChild(String name) { this.name = name; } public GenericChild(T t, String name) { super(t); this.name = name; } public GenericChild(T t, String name, E e) { super(t); this.name = name; this.e = e; } //getter/setter 方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public E getE() { return e; } public void setE(E e) { this.e = e; } //重写的父类的方法 @Override public void sayHello(T t, String name) { System.out.println("Hello "+name+";This is Child T : "+t); } //对 E 类型的成员变量自己写的一个方法 public void sayE(){ System.out.println("This is child e : "+e); } //toString 方法 @Override public String toString() { return "GenericChild{" + "name='" + name + ''' + '}'; } }
public class CommonChild extends GenericFather2.4 创建子类的对象使用{ @Override public void sayHello(Integer integer, String name) { super.sayHello(integer, name); } }
public class Application {
public static void main(String[] args) {
//1.泛型类的子类
GenericChild child = new GenericChild<>();
// 子类中明确指定的属性 String name
child.setName("child");
// 继承自父类中的泛型类型 T t
child.setT("T-child");
//自己扩展的泛型类型 E e
child.setE(100);
// 调用重写的父类的方法
child.sayHello("泛型",child.getT()); // Hello T-child;This is Child T : 泛型
//调用自己写的方法
child.sayE(); // This is child e : 100
System.out.println("=========================================");
//2.非泛型类的子类
CommonChild commonChild = new CommonChild();
commonChild.sayHello(200,"普通的子类");
}
}
2.5 运行结果
Hello T-child;This is Child T : 泛型 This is child e : 100 ========================================= Hello 普通的子类;This is father T : 2003.完成
Congratulation!
You are one step closer to success!



