I genius the official free tutorial 30: Java Basic Tutorial Generics

Source: Internet
Author: User
Tags case statement

generic type

Let me give you an example: now there is a factory that can produce mobile phones or make computers. Other products may also be produced in the future.
If you add generics to a factory, the factory can only produce mobile phones or computers and no longer produce other products.

Example: Package generic;/** * Product Enumeration Products * @author Genius Federation-Yukun */public enum Product {phone, PC}package generic;/** * Mobile phone * @au Thor Genius Alliance-Yukun */public class Phone {/** * method for calling */public void call () {System.out.println ("Make a Call");}} Package generic;/** * Computer class computer * @author Genius Alliance-Yukun */public class Computer {/** * method of writing code */public Void Coding () {Syste M.out.println ("Writing Code");}}
package generic;/** *  General Factory class factory: For comparison with generic plant class  *  @author   Genius Alliance  -  Yukun  */public class Factory {/** *  Create return value type object[], function is to produce multiple product objects  *  Because there are multiple product types, the return value takes all products in common with the parent type OBJEC array  */public object[] getproduct () {//  Create a one-dimensional array of type Object of length 2 , you can store your phone, or you can hold your computer object[] products = new object[2];//  create a phone object, and put it in the array subscript 0 position Products[0]  = new phone ();//  Create a computer object and deposit the position labeled 1 in the array products[1] = new computer ();//  Returns an array of productsreturn products;} /** *  create the corresponding product according to the parameter value  *  if you need to use this method to create another product later, add the case statement in the switch statement, poor extensibility  */public  Object[] getproduct (Product producttype) {//  creates a one-dimensional array of type object of length 2 that can be stored on the phone or stored on the computer object[]  products = new object[2];switch  (producttype)  {case  phone://  Create a phone object, Deposit the position labeled 0 in the array products[0] = new phone ();/* *  even if the value of ProductType is the phone, the computer object can still be stored here  *   If this is mistakenly created as CThe Omputer object, when acquired, is most likely to be mistakenly converted to phone type  *  resulting in a type conversion exception, robustness (security) Difference  */products[1] = new computer ();break;case  computer://  Create two computer objects to be stored in an array products[0] = new computer ();p roducts[1] =  new computer (); break;}   return array productsreturn products;}}
package generic;import java.lang.reflect.array;/** *  generic Factory class Genericfactory<t>: Used to demonstrate generics  *  where T is the formal parameter of the type Genericfactory class  *  use type Genericfactory can pass in a type (class name) as an argument  *  You can use T as a data type inside the type Genericfactory  *  for example:genericfactory<string> so that all T in the compiled class will be replaced with string *   * t is commonly referred to as a placeholder here, or it can be any other symbol that matches the naming rules of an identifier  *  commonly used for the first letter of T and E,t:type (type); E:element (Element) first letter  *   *  If you need to use more than one generic, the middle of the placeholder is separated by commas in the English format  *  for example:genericfactory<t,e> *  It is also used in the order of location to pass in  *  for example:genericfactory<string,integer> *  all T in its class is replaced with a String, All e will be replaced with integer *  *  @author   Genius Alliance  -  Yukun  */public class  genericfactory<t> {/** *  declares a return value of type t[] (an array of type T), the method of the object with the parameter class type  *  the method used to obtain the factory's product  */public t[] getproduct (CLASS&LT;T&GT;&NBSP;CLS) {//Create an array of length 2,t type T; The beginner's classmates know the following code is useful t[] t  =  (t[])  array.newinstance (CLS,&NBSP;2); try {//creates an object of type T; equivalent to  t = new t (); T[0] = cls.newinstance ();t[1] =  Cls.newinstance ();}  catch  (instantiationexception e)  {e.printstacktrace ();}  catch  (illegalaccessexception e)  {e.printstacktrace ();} Returns the object Treturn t;}}
package generic;/** *  Generic test class generictest *  for testing and comparing the use of two plants  *  @author   Genius Alliance  -  Yukun  */public class generictest {public static void main (String[ ] args)  {//Create a generic Factory object Ffactory f = new factory ();// The product array obtained through the GetProduct method of factory F is an array of type object//So there may be multiple products stored in this array object[] products = f.getproduct ( Product. mobile); When you remove a product from an array that is of type object, you need to force the type conversion phone fp =  (phone) products[0];// Method of calling using the Mobile object FP call Callfp.call ();/* *  We know that at this point the product labeled 1 is computer  *  if the user does not know what type of product is stored in the product array, Still cast it to phone type  * Phone fp =  (phone) products[1]; Type conversion exception occurs &NBSP;*/COMPUTER&NBSP;FC  =  (computer) products[1];fc.coding (); System.out.println ("--------------");/* *  creates a generic factory object phonefactory, the generic factory's parameter T position is passed in phone *  So the factory phonefactory can only produce mobile phones, can not produce computer  *  if you want to produce a computer, you need to create a production computer factory  */GenericFactory<Phone>  Phonefactory = new genericfActory<phone> ();//production of mobile phones through generic factory phonefactory, parameters can only be passed in phone.classphone[] phone =  Phonefactory.getproduct (Phone.class);p hone[0].call ();//Create a computer factory and only produce computers genericfactory<computer>  Computerfactory = new genericfactory<computer> (); Computer[] computer = computerfactory.getproduct (Computer.class); computer[0].coding ();}} Run Result: Call to write code--------------call to write code


Summary:

Storing child class objects using a parent type array
Pros: You can store any type of subtype
Disadvantage: When you get an object from an array and call a specific method in a subclass, you need to force the type conversion
There is a risk of type conversion exceptions
Using generic arrays
Pros: Get object infinite coercion type conversion, there is no risk of type conversion exception
Type of extensibility is good
Cons: Creating generic-related instances trouble
When used, the generic type is fixed once the parameter is passed in, resulting in a single type (for example, two generic factories above, you can see two different types)


Generics are equivalent to adding a parameter to a type, similar to a method with parameters, the parameter of a method is a variable that declares a data type, a parameter is enclosed in parentheses, the passed argument is a value or an object of a data type, and a parameter variable can be used within a method, and the type's formal parameter is just a placeholder, surrounded by angle brackets The passed-in argument is a type (class name), and the placeholder can be used as a data type within the class;
The most generic application is a collection.


This article from the "Genius Union Education Official Blog" blog, reproduced please contact the author!

I genius the official free tutorial 30: Java Basic Tutorial Generics

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.