泛型类型的继承规则可能不能凭直觉的来想当然。下面举个例子来看看泛型类型的继承规则。
首先有几个辅助类:
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; } }
原文地址:http://blog.csdn.net/l294265421/article/details/46413975