The understanding of Java generic Extends,super and wildcard characters __java

Source: Internet
Author: User
Tags gety object object
characteristics of 1.java genericsTypically, a compiler handles generics in two ways:
1.Code Specialization. A new target code (byte code or binary) is generated when instantiating a generic class or generic method. For example, for a generic list, you might need to generate three target codes for string,integer,float.
2.Code sharing. Only one copy of the target code is generated for each generic class, and all instances of the generic class are mapped to the target code, performing type checking and type conversion when needed.
The template in C + + (template) is a typical code specialization implementation. The C + + compiler generates an execution code for each instance of a generic class. The integer list and string list are two different types in the execution code. This can lead to code bloat, but experienced C + + programmers have the knack of avoiding code bloat.
Code specialization Another disadvantage is wasting space in reference type systems, because the elements in a reference type collection are essentially a pointer. There is no need to generate an execution code for each type. This is also the main reason that the Java compiler uses the code sharing method to handle generics.
The Java compiler creates a unique bytecode representation for each generic type by means of the code sharing and maps instances of that generic type to this unique byte-code representation. Mapping multiple generic class instances to a unique byte-code representation is accomplished by type erase (kind erasue). 2. What is type erasure.

Type erasure refers to a combination of type parameters that associates a generic type instance to the same byte code. The compiler generates only one byte code for the generic type and associates its instance with this byte code. The key to type erasure is to clear the information about the type parameters from the generic type, and to add a method of type checking and type conversion when necessary.

Type erasure can be simply interpreted as converting generic Java code to normal Java code, except that the compiler is more straightforward and converts generic Java code directly to normal Java bytecode.
The main process for type erasure is as follows:
1. Replace all generic parameters with their leftmost boundary (top-level parent type) type.
2. Remove all the type parameters. Introduction to 3.extends,super and wildcard characters 1.extends extends not only can be used to represent inheriting a parent class, it can be used on the definition of a generic class. Indicates that the parameter type inherits from a class or implements an interface. Exte NDS and & can be used to represent types and interfaces that a parameter type must inherit and implement. Note that there can be only one class in the type parameters of the extends and &, and the rest are interfaces. Use the following

package generics;

Class o<t>{T item;}
  Class Holditem<t> {T item;
  Holditem (T item) {This.item = Item;}


T GetItem () {return item;}}
  Class Colored2<t extends hascolor> extends holditem<t> {Colored2 (T item) {super (item);}

Java.awt.Color Color () {return Item.getcolor ();}} Class Coloreddimension2<t extends Dimension & hascolor> extends Colored2<t> {ColoredDimension2 (T Item)
  {super (item);}
  int GetX () {return item.x;}
  int GetY () {return item.y;}

int GetZ () {return item.z}} Class Solid2<t extends Dimension & hascolor & weight> extends Coloreddimension2<t> {Solid2 (T Item)
  {super (item);}

int weight () {return item.weight ();}} public class Inheritbounds {public static void main (string[] args) {solid2<bounded> Solid2 = new Solid
    2<bounded> (new bounded ());
    Solid2.color ();
    Solid2.gety ();
  Solid2.weight (); }
} ///:~
2.extends,super and. Wildcard characters are used together
Import java.util.*;

Class Fruit {} class
Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}
public class Genericsandcovariance {public
  static void Main (string[] args) {
    //wildcards allow covariance:
    list<? Extends fruit> flist = new arraylist<apple> ();
    Flist=new arraylist<orange> ();
    Compilation failed, cannot add any type
    //flist.add (new Fruit ());
    Flist.add (New Object ());
    Flist.add (New Object ());
    We know that it returns at least Fruit:
    Fruit f = flist.get (0);
    list<? Super Fruit> list = new arraylist<fruit> ();   
    List.add (New Apple ());//Can be   
    list.add (new Fruit ());//Can   
    List.add (new Jonathan ());
  }
///:~</ Span>
      List<?extends fruit> flist=new arraylist<apple> () indicates that the List referenced by Flist is a subclass of Fruit. Specifically Apple or orange does not know, so in the use of List.add type is actually. Extends Fruit, you cannot use Add to add any objects, including object and Fruit objects, because if you can, you can add an orange object to Apple's list by Flist.add ((Fruit) New Orange ()). Get actually returns object object and then transitions to fruit, so it can be used. The     Super keyword indicates that the referenced list is a fruit or fruit parent class. So you can add oragnge,apple to the list because they are all fruit subtypes. Verify the following again
Package generics;
  public class Holder<t> {private T value;
  Public Holder () {} public Holder (T val) {value = val;}
  public void Set (T val) {value = val;}
  Public T get () {return value;}
  public boolean equals (Object obj) {return value.equals (obj);
    public static void Main (string[] args) {holder<apple> Apple = new Holder<apple> (new Apple ());
    Apple d = apple.get ();
    Apple.set (d); holder<fruit> Fruit = Apple; Cannot upcast holder<? Extends fruit> Fruit = Apple;
    OK Fruit p = fruit.get (); D = (Apple) fruit.get (); Returns ' Object ' try {orange c = (orange) fruit.get ();//No warning} catch (Exception e) {SYSTEM.OUT.PR Intln (e); //Fruit.set (New Apple ()); Cannot call set ()//Fruit.set (new fruit ()); Cannot call set () System.out.println (Fruit.equals (d));
 OK}}/* Output: (Sample) Java.lang.ClassCastException:Apple cannot is cast to Orange true *///:~




Related Article

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.