Inheritance rules for generic types may not be taken for granted by intuition. Let's take a look at the inheritance rules for generic types, for example.
There are several helper classes first:
Package Generic;public class Person extends Animal {private string name;public person (String name) {super (); this.name = NA Me;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} @Overridepublic String toString () {return "person [name=" + name + "]";}}
Package Generic;public class Student extends person {private String studentnumber;public Student (string name, String regis Trationnumber) {super (name); this.studentnumber = Registrationnumber;} Public String Getstudentnumber () {return studentnumber;} public void Setstudentnumber (String studentnumber) {this.studentnumber = Studentnumber;} @Overridepublic String toString () {return "Student [studentnumber=" + Studentnumber + ", name=" + getName () + "]";}}
here is the test class:
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 description, although Student is a subclass of person, * arraylist<student> is not a subclass of 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 Description arraylist<person> is a subclass of * list<student> */list<student> students2 = Students;}}
test1 and test2 indicate that a generic type inherits only in the dimension of the class, and the type variable must be the same, such as Arraylist<e> implements List<e>.
Inheritance rules for Java generic generic types