通过例子来看泛型类在继承中过程中类型变量应该具有怎样的关系。
首先给出几个辅助类:
package generic; public class Animal { }
package generic; public class Person extends Animal { private String name; public Person(String name) { super(); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Person [name=" + name + "]"; } public Integer printAndReturn() { return 1; } }
package generic; public class Student extends Person { private String studentNumber; public Student(String name, String studentNumber) { super(name); this.studentNumber = studentNumber; } public String getStudentNumber() { return studentNumber; } public void setStudentNumber(String studentNumber) { this.studentNumber = studentNumber; } @Override public String toString() { return "Student [studentNumber=" + studentNumber + ", name=" + getName() + "]"; } }
package generic; public class Building { private String name; public Building(String name) { super(); this.name = name; } }
package generic; /** * @version 1.00 2004-05-10 * @author Cay Horstmann */ public class Pair<T extends Person> { private T first; private T second; public Pair() { first = null; second = null; } public Pair(T first, T second) { this.first = first; this.second = second; } public T getFirst() { return first; } public T getSecond() { return second; } public void setFirst(T newValue) { first = newValue; } public void setSecond(T newValue) { second = newValue; } }
1.子类的类型变量表示的范围必须与父类一样或者是父类的子集
package generic; public class PariSon<T extends Person> extends Pair<T> { }
或
public class PariSon<T extends Student> extends Pair<T> { }
2.当父类用具体类型代替类型变量时,具体变量必须是类型变量表示的范围内的一个元素
package generic; public class PariSon extends Pair<Person> { }
或
package generic; public class PariSon extends Pair<Student> { }
时间: 2024-10-17 11:08:57