Java generic instance details (generic, wildcard, generic interface)

Source: Internet
Author: User

Java generic description (generic, wildcard, generic interface) 2013-02-04 19:49:49|  Category: JAVA | Tags: java | report | font size subscription Download Lofter Client JDK1.5 We've been looking for a long time, but when he released it, he changed the version number to 5.0. This suggests that there has been a significant change in Java. This article explains the new features supported by JDK5.0-----generics for Java. 1, Java Generics in fact, Java is a generic type that creates a class that uses types as parameters. Just like the way we write a class, the method is such methods (String str1,string str2), and the values of the parameters str1 and str2 in the method are variable. The generic is the same, so write class Java_generics <K,V>, where the side of the K and V is like the parameters of the method str1 and str2, is also variable. To write a generic class Note: 1) when defining a generic class, define a formal type parameter between "<>", for example: "Class TestGen <K,V>", where "K", "V" does not represent a value, but represents a type. 2) When instantiating a generic object, be sure to specify the value (type) of the type parameter after the class name, and write two times. For example: TestGen <String,String> t=new TestGen <String,String> (); 3) <k extends object>,extends in generics does not represent inheritance, it is a type range limitation. Generic Java code class point<t>{//Here can be casually write the identity symbol, T is the type of the abbreviation for the private t var;//var is specified by T, i.e.: externally specified public T g      The type of the Etvar () {//return value is determined by the external return var;      The type of public void SetVar (T var) {//set is also determined externally by This.var = var;  }  }; public class genericsdemo06{public static void Main (String args[]) {point<string> p = new Point<st Ring> (); The Var insideType is String type P.setvar ("it");   Sets the string System.out.println (P.getvar (). Length ());  Gets the length of the string}}; ----------------------------------------------------------class notepad<k,v>{//Two generic types specified here private K     Key;   The type of this variable is determined externally by private V value;      The type of this variable is determined externally by the public K GetKey () {return this.key;      } public V GetValue () {return this.value;      } public void Setkey (K key) {this.key = key;      public void SetValue (V value) {this.value = value;  }  }; public class genericsdemo09{public static void Main (String args[]) {notepad<string,integer> t = null        ;       Defines an object of two generic types T = new notepad<string,integer> ();        The key inside is string,value for the integer T.setkey ("Tom");            Set the first content of T.setvalue (20);      Set a second content System.out.print ("name;" + T.getkey ()); Obtain information System.out.print (", age;") + T.getvalue ());   Get information}};     Wildcard Java code class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;      } public String toString () {//Direct print return this.var.toString ();  }  }; public class genericsdemo14{public static void Main (String args[]) {info<string> i = new Info<stri       Ng> ();                            Use string for generic type I.setvar ("it");      Set content fun (i);      public static void Fun (Info<?> temp) {//can receive arbitrary generic object System.out.println ("content:" + temp);   }  };     Restricted generic Java code class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;      } public String toString () {//Direct print return this.var.toString ();  }  }; public class Genericsdemo17{public static void Main (String args[]) {info<integer> i1 = new info<integer> ();            A generic object that declares an integer info<float> i2 = new info<float> ();                                 Declares a generic object of float I1.setvar (30);                              Set integer, Auto boxing i2.setvar (30.1f);          Set decimal, Auto boxing fun (i1);      Fun (I2);  } public static void Fun (INFO&LT;? extends Number> temp) {//can only receive subclasses of number and its number System.out.print (temp      + ",");  }  };     ----------------------------------------------------------class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;      } public String toString () {//Direct print return this.var.toString ();  }  }; public class genericsdemo21{public static void Main (String args[]) {info<string> i1 = new Info<stRing> ();      A generic object that declares a string info<object> i2 = new info<object> ();          A generic object that declares object I1.setvar ("Hello");          I2.setvar (New Object ());          Fun (I1);      Fun (I2); } public static void Fun (INFO&LT;? Super String> temp) {//can only receive generic System.out.print of type String or object (TEM      P + ",");   }  };     Generics cannot be transformed upward Java code class info<t>{private T var;      Defines a generic variable public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;      } public String toString () {//Direct print return this.var.toString ();  }  }; public class genericsdemo23{public static void Main (String args[]) {info<string> i1 = new Info<str      Ing> ();          The generic type is string info<object> i2 = null;                               I2 = I1;   This sentence will go wrong incompatible types}}; Generic interface Java Code interface info<t>{//define generic P on interfaceUblic T GetVar ();             Defines the abstract method, the return value of the abstract method is the generic type} class Infoimpl<t> implements info<t>{//defines the generic interface subclass of the private T var;        Define the property public Infoimpl (T var) {//Set property content This.setvar (Var) by constructing method;      } public void SetVar (T var) {this.var = var;      } public T GetVar () {return this.var;  }  };        public class genericsdemo24{public static void Main (String arsg[]) {info<string> i = null;  Declares the interface object i = new Infoimpl<string> ("Tom");      Instantiate an object by subclasses System.out.println ("content:" + I.getvar ());  }  }; ----------------------------------------------------------interface info<t>{//define the generic public T Getv on the interface AR ();                Defines the abstract method, the return value of the abstract method is the generic type} class Infoimpl implements info<string>{//defines the subclass of the generic interface private String var;        Defines the property public Infoimpl (String var) {//Set property content This.setvar (Var) by constructing the method; } public voidSetVar (String var) {this.var = var;      } public String GetVar () {return this.var;  }  };      public class genericsdemo25{public static void Main (String arsg[]) {Info i = null;    Declares the interface object i = new Infoimpl ("Tom");      Instantiate an object by subclasses System.out.println ("content:" + I.getvar ());   }  };                  Generic method Java code class demo{public <T> t Fun (T T) {//can receive any type of data return T;  Return the parameter directly}};   public class genericsdemo26{public static void Main (String args[]) {Demo d = new demo (); Instantiate the Demo object String str = d.fun ("Tom");     Pass the string int i = D.fun (30);   Pass number, auto boxing System.out.println (str);     Output content System.out.println (i);   Output content}};     Returns a generic type instance through a generic method Java code class Info<t extends number>{//Specify upper limit, can only be numeric type private T var;         This type is determined externally by the public T GetVar () {return this.var; } public void SetVar(T var)      {This.var = var;          } public String ToString () {//overwrite the toString () method in the object class return This.var.toString ();  }  };          public class genericsdemo27{public static void Main (String args[]) {info<integer> i = fun (30);      System.out.println (I.getvar ()); } public static <t extends number> info<t> (T param) The generic type that is passed in or returned from the {///method is determined by the type of parameter that is set when the method is called info<      t> temp = new info<t> ();        Instantiate info Temp.setvar (param) Based on the data type passed in;   Set the passed content to the Var attribute of the Info object return temp;   Returns the instantiated object}};     Use generic uniform incoming parameter type Java code class info<t>{//Specify upper limit, can only be numeric type private T var;         This type is determined externally by the public T GetVar () {return this.var;      } public void SetVar (T var) {this.var = var;          } public String ToString () {//overwrite the toString () method in the object class return This.var.toString ();  }  }; public class genericsdemo28{Public static void Main (String args[]) {info<string> i1 = new info<string> ();          info<string> i2 = new info<string> ();        I1.setvar ("HELLO");       Set content I2.setvar ("Tom");      Set content Add (I1,I2); } public static <T> void Add (info<t> i1,info<t> i2) {System.out.println (I1.getvar () + ""      + I2.getvar ());   }  }; Generic array Java code public class genericsdemo30{public static void Main (String args[]) {Integer i[] = fun1 (1,2,3,4,5,   6);      Returns the generic array fun2 (i);            } public static <T> t[] Fun1 (t...arg) {//Receive variable parameter return arg;          return generic array} public static <T> void Fun2 (T param[]) {//Output System.out.print ("Receive generic array:");          for (t T:param) {System.out.print (t + ",");   }      }  };      Nested settings for generics Java code class info<t,v>{//Receive two generic type private T var;      private V value; Public Info (T var, V value) {This.setvar (VAR);      This.setvalue (value);      } public void SetVar (T var) {this.var = var;      public void SetValue (V value) {this.value = value;      } public T GetVar () {return this.var;      } public V GetValue () {return this.value;  }  };      Class demo<s>{private S info;      Public Demo (S info) {This.setinfo (info);      } public void SetInfo (S info) {this.info = info;      } public S GetInfo () {return this.info;  }  }; public class genericsdemo31{public static void Main (String args[]) {demo<info<string,integer>>       d = null;   Use Info as the generic type of the demo info<string,integer> i = null;    INFO specifies two generic type I = new info<string,integer> ("Tom", 30); Instantiate Info Object d = new demo<info<string,integer>> (i); Set the object of the info class in the Demo class System.out.println ("content one:" + d.getInfo (). GetVar ());      SYSTEM.OUT.PRINTLN ("Content two:" + D.getinfo (). GetValue ()); }  };

Java generic instance details (generic, wildcard, generic interface)

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.