Inheritance rules for Java generic generic types

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.