泛型类型的继承规则可能不能凭直觉的来想当然。下面举个例子来看看泛型类型的继承规则。
首先有几个辅助类:
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 + "]"; } }
package generic; public class Student extends Person { private String studentNumber; public Student(String name, String registrationNumber) { super(name); this.studentNumber = registrationNumber; } 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; import java.util.ArrayList; import java.util.List; public class Test2 { public static void main(String[] args) { // TODO Auto-generated method stub // test1 /** * test1说明,虽然Student是Person的子类,但是 * ArrayList<Student>并不是ArrayList<Person> * 的子类 */ ArrayList<Student> students= new ArrayList<Student>(); // error /** * Type mismatch: cannot convert * from ArrayList<Student> to ArrayList<Person> */ ArrayList<Person> persons = students; // error // test2 /** * test2说明ArrayList<Person>是 * List<Student>的子类 */ List<Student> students2 = students; } }
test1和test2说明泛型类型只在类这个维度继承,类型变量必须一样,如ArrayList<E> implements List<E>。
时间: 2024-11-07 08:02:05