Inheritance rules for Java generic classes

Source: Internet
Author: User
Tags object object

First look at the use of the Java generic class:

/*** A generic method: Makes the program more secure * and can be used more *@authorDing * * *@param<T>*/classPair<t>{    PrivateT first; PrivateT Second; //Instantiating type variables     Public Static<T> pair<t> Makepair (class<t>cl) {        Try {            return NewPair<>(Cl.newinstance (), cl.newinstance ()); } Catch(Exception e) {return NULL; }     }         PublicPair () {first =NULL; Second =NULL; }  PublicPair (t first, t second) { This. first = first; This. Second =second;}  PublicT GetFirst () {returnFirst ; }     Public voidSetfirst (T first) { This. First =First ; }     PublicT Getsecond () {returnsecond; }     Public voidSetsecond (T second) { This. Second =second; }    }
class Father {    privateint age = +;      Public void GetName () {        System.out.println (age);    }} class extends father{    privateint age =N;      Public void GetName () {        System.out.println (age);    }}

In the normal class: Father AA = new Son (); The parent class is the one that can be used to point to subclasses.

However, this is not the case in a generic class:

New Pair<>(); Pair<Father> cc = BB; // Error
1: Although son is a subclass of father, there is no inheritance relationship between pair<t>:

New Arraylist<>(); ListNew arraylist<>(); // setting A1 can be equal to A2 // a1 = A2; // A1.add (1111); You can add Object,a1.add (Object AD) because it is a A1 operation; // a2.get (0) error, because A1 added an object into the A2 space, but A2 is a string type, so error

2: You can convert a parameterized type to an original type:
New arraylist<>= A2; // you can compile, but you might get a type error when you use the method later!  // This time the A3 object is the original type, so Add (object obj); A3.add (123); // is to operate on the A3, but the final result is saved in A2, and it is obviously wrong to load an integer into the string;

3: Generic classes can extend or implement other generic classes:
 //  generic interface   Interface  list1<e>{}  // Span style= "COLOR: #008000" to implement generic interface generics class  class  list2<t, e> implements  list1<e>{}  //  generic class  class  list3<t >{}  //  Generic class that inherits other generic classes  class  list4<t, e>  Extends  list3<e>{}  
New List2<son, father> (); // because List2 realized the List1 New List4<son, father> (); // List4 inherits the List3, so List3 is the parent class that can point to the subclass object.

Although this also accomplishes the inheritance of generic classes and implements the same polymorphism as the normal class, it is not particularly good to use, so Java introduces the wildcard concept:

Maximum wildcard characters:
 /*     pair<? Extends father> c2extends is the keyword pair<t> represents a generic class for a unique (Specific generic class): For example pair<son>,pair<father> but pair< ? Extends father> is not a specific generic class, it refers to all generic classes (including Father) of subclasses of the parameter type Father  */. Span style= "COLOR: #000000" >pair  <? extends  Father> C3; Pair  <Father> c1 = new  pair<> () ; Pair  <Son> c2 = new  pair<> ();  // C2 = C1;error  c3 = c1;c3  = C2; 

It is important to note that:

/* * The problem with the upper limit of wildcards: *? extends Father getfirst (); * void Setfirst (? extends Father); * When c2= C1: * C2.setfirst (Father Father) , the Father object is added to the Son object memory, which is not good * so when using the extends cap, you cannot use Setfirst (? extends Father), add (? extends Father) *, and so on. * But you can use the GetFirst () method */ 
C2.setfirst (new Father ();); /error
Wildcard lower limit:

/* * The lower limit of the wildcard: *? Super son* represents not a specific generic class, but rather represents all possible generic classes of the parent class of the parameter type Son (including * * Son)
* As with wildcard caps, wildcard qualifier cannot use the GetFirst () method, but you can use the Setfirst (XX) method */Pairnew pair<> (); PairSuper son>= C1;

Another type of super-restrictive notation
Pair<t extends Comparable<? Super t>> C4;

unqualified wildcard characters:

// Unqualified wildcard characters New Pair<>(); PairNew pair<>(); // c7 = C5;error because they are not of the same type New pair<>= c5; // Pair<?> is the parent class of all the Pair generic classes,pair<?> c6 = new pair<xx> ();

The essential difference between pair<?> and pair is that the SetObject () method of the original pair class can be invoked with arbitrary object object.

capture of wildcard characters:
 //  interchange First,second variable value  public  static  void  Swap (Pair<?> p) {? t = P.getfirst ();   error because the wildcard character (? ) is not a type variable, so it cannot be directly Write code that solves this problem with a wildcard capture.          P.setfirst (P.getsecond ());    P.setsecond (t); }
 //  interchange First,second variable value  public  static  void  Swap (Pair<?> p) {Swaphelper (p);  //  }  //  Use a wildcard capture to resolve the problem  public  static  <t > void  swaphelper (pair<t> p) {T T  = P.getfirst (); // t is a specific type.          P.setfirst (P.getsecond ());    P.setsecond (t); }

Note: The wildcard capture is only legal in the case of many limitations, and the compiler must be able to be sure that the wildcard expression is a single, deterministic type.

Inheritance rules for Java generic classes

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.