Java Basics: Enum enum

Source: Internet
Author: User

In some cases, the object of a class is limited and fixed, such as the season class, it has only 4 objects: Spring, summer, autumn, winter. This example of a finite and fixed class, in Java, is called an enumeration class.

1 Manually implementing an enumeration class

Example:

package com.demo2;public class season {public static final season  Spring = new season ("Spring",  "while spring outing");p Ublic static final season summer  = new season ("Summer",  "summer scorching");p ublic static final season fall =  new season ("Autumn",  "crisp");p ublic static final season winter = new  season ("Winter",  "Wai Furnace View Snow");p Ublic static season getseason (int seasonnum)  {switch   (Seasonnum)  {case 1:return SPRING;case 2:return SUMMER;case 3:return  Fall;case 4:return winter;default:return null;}} Private final string name;private final string desc;private season (String  NAME, STRING DESC)  {this.name = name;this.desc = desc;} Public string getname ()  {return name;} Public string geTdesc ()  {return desc;}} 
Package Com.demo2;public class Test2 {public Test2 (Season s) {System.out.println (S.getname () + "-----" + s.getdesc ());} public static void Main (string[] args) {new Test2 (season.spring);}}

If you need to implement enumerations manually, you can design them as follows:

    • The constructor is hidden by private.

    • All instances of this class are saved using the public static final modified class variable.

    • If necessary, provide some static methods that allow other programs to obtain an instance of the match based on a specific parameter.

PS: Some programmers prefer to use a simple definition of several static constants to represent an enumeration class.

For example:

public static final int season_spring=1;public static final int season_summer=2;public static final int Season_fall=3;publ IC static final int season_winter=4;

There are several problems with this approach:

    • Type is not secure. Examples are all integral types, so the seasons can be +,-,*,/and other int operations.

    • No namespace. These static constants can only be divided by the prefix "Season_" to classify the owning type.

    • Printed output, meaning unclear. If you use System.out.println () to print the season_spring, the output is 1, not SPRING.

2 Enum class enum

JDK 5 has a new keyword enum, which is the same as class,interface and is used to define enumeration classes. The enumeration class is actually a special class, it can have its own field, method, constructor, can implement one or more interfaces.

2.1 Defining enumeration Classes

Example:

Package Com.demo2;public enum seasonenum{spring, SUMMER, FALL, WINTER;}

Compiling the code will generate a Seasonenum.class file stating that the enumeration class is a special class.

When defining an enumeration class, it is necessary to explicitly list all enumerated values, such as spring, SUMMER, FALL, WINTER above, and all enumeration values are separated by commas (,), ending with a semicolon as the enumeration value. These enumeration values represent all possible instances of the enumeration class.

2.2 Enumeration Class Nature

To decompile the Seasonenum.class file generated in 2.1:

Javap-c Seasonenum.class > SeasonEnum.txt

The results are as follows:

compiled from  "Seasonenum.java" public final class com.demo2.seasonenum extends  java.lang.Enum<com.demo2.SeasonEnum> {  public static final  com.demo2.seasonenum spring;  public static final com.demo2.seasonenum  summer;  public static final com.demo2.seasonenum fall;  public  static final com.demo2.seasonenum winter;  static {};     code:       0: new             #1      // class com/demo2/SeasonEnum        3: dup                   4: ldc             #15     // string spring       6: iconst_0              7: invokespecial  #16     //  method  "<init>":(ljava/lang/string;i) v      10: putstatic       #20     // Field SPRING:Lcom/demo2/SeasonEnum;       13: new            #1 &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//&NBSP;CLASS&NBSP;COM/DEMO2/SEASONENUM&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;16:  dup                  17: ldc            #22      // String SUMMER      19: iconst_1             20: invokespecial  #16     // Method  "<init>":( Ljava/lang/string;i) v      23: putstatic      #23     // field summer:lcom/demo2/seasonenum;      26 : new            #1      //  class com/demo2/SeasonEnum      29: dup                  30: ldc             #25     // String FALL       32: iconst_2             33: invokespecial  #16     // Method  <init>:(ljava/ Lang/string;i) v      36: putstatic      #26     //  field fall:lcom/demo2/seasonenum;      39: new             #1      // class com/demo2/ seasonenum      42: dup                  43: ldc             #28     // String WINTER       45: iconst_3            46:  invokespecial  #16     // Method  "<init>":(ljava/lang/string;i) v       49: putstatic      #29     //  field winter:lcom/demo2/seasonenum;      52: iconst_4             53: anewarray      #1      //  class com/demo2/SeasonEnum      56: dup                  57: iconst_0             58: getstatic     # 20    // field spring:lcom/demo2/seasonenum;       61: aastore             62: dup &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;63:  iconst_1            64: getstatic       #23 &nbsP;&NBSP;&NBSP;&NBSP;//&NBSP;FIELD&NBSP;SUMMER:LCOM/DEMO2/SEASONENUM;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;67:  aastore             68: dup                  69:  iconst_2            70: getstatic       #26     // Field FALL:Lcom/demo2/SeasonEnum;       73: aastore              74: dup                  75: iconst_3            76:  getstatic      #29     // field winter:lcom/demo2/ Seasonenum;   &nbsP;  79: aastore             80 : putstatic      #31     // field enum$values:[lcom/ demo2/seasonenum;      83: return           public static com.demo2.seasonenum[] values ();     Code:        0: getstatic      #31      // Field ENUM$VALUES:[Lcom/demo2/SeasonEnum;       3:  dup                   4: astore_0             5:  iconst_0             6: aload_0               7: arraylength           8: dup                   9: istore_1             10: anewarray      #1      //  class com/demo2/SeasonEnum      13: dup                  14: astore_2             15: iconst_0             16: iload_1              17: invokestatic   #39     // Method  Java/lang/system.arraycopy: (Ljava/lanG/OBJECT;ILJAVA/LANG/OBJECT;II) v      20: aload_2              21: areturn          public static com.demo2.seasonenum valueof (java.lang.String);     Code:       0: ldc             #1     // class com/demo2/SeasonEnum        2: aload_0               3: invokestatic   #47    // method java/lang/ Enum.valueof: (Ljava/lang/class; ljava/lang/string;) ljava/lang/enum;       6: checkcast       #1     // class com/demo2/SeasonEnum         9: areturn       } 

Java.lang.Enum's source structure is as follows:

According to bytecode and Java.lang.Enum source structure can draw the following conclusions:

    • Enum classes defined with enum inherit directly from the Java.lang.Enum class by default, rather than inheriting java.lang.Object directly. Among them, Java.lang.Enum realized Java.lang.comparable<e> Java.lang. Serializable two interfaces.

    • Enum classes that use enum definitions and non-abstractions use the final adornment by default, so non-abstract enumeration classes cannot derive subclasses.

    • The constructor for an enumeration class can only use the private access control. If you omit the access control for the constructor, the private adornment is used by default, and if you force the access control to be specified, only private is used.

    • All instances of an enumeration class must be listed in the first row of the enumeration class, or the enumeration class will never produce an instance. When these instances are listed, the public statci final modifier is added automatically without the programmer's display.

The nature of the Java implementation enumeration:

  • Java.lang.Enum defines the constituent components of an enumeration object. An Enumeration object contains two properties "ordinal" and "name", a series of instance methods, such as ToString, CompareTo, and so on. "Ordinal" is the index value, based on the location of the enumeration declaration, starting at 0. "name" is the name of the enumeration object. For example public enum seasonenum{spring, SUMMER, FALL, WINTER;} , Spring's index value is 0,name "Spring";SUMMER 's index value is 1,name "SUMMER" ...

  • At compile time, the compiler (JAVAC) adds a static{} initialization block to the. class file of the custom enumeration class, and the initialization block includes instructions for generating the enumeration object. in the sample bytecode, the static{} initialization block sequentially generates a spring enumeration object and assigns an index value of 0,name to "Spring", generates a summer enumeration object and assigns the value of the index value 1,name to " SUMMER "..... Finally, a static member "Enum$values" is also defined in the Seasonenum class, which is an seasonenum array that holds the indexed object sequentially, based on the "ordinal" value of the indexed object.

2.3 Enumerating classes and switch structures

If you need to use an instance of an enumeration class, you can use the form enumeration class. An instance, such as seasonenum.spring.

Example:

Package Com.demo2;public class Test {public static void judge (Seasonenum s) {switch (s) {case SPRING:System.out.println ("Spring Days, while spring outing "), Break;case SUMMER:System.out.println (" Summer, Summer scorching "), Break;case FALL:System.out.println (" Autumn, crisp "); Case WINTER:System.out.println ("Winter, snow in the surrounding Furnace"); public static void Main (string[] args) {judge (Seasonenum.fall);}}

In the switch expression in the above program, the Seasonenum object is used as an expression, which is the extension to switch after JDK 5 adds enumeration: The control expression of switch can be any enumeration type. Not only that, when the switch control expression uses an enumeration type, the value in the following case expression uses the enumeration value name directly, without adding an enumeration class as a qualification.



3 enumeration classes and constructors


4 Enumerating classes and interfaces



5 enumeration classes and abstract methods

Cond








Java Basics: Enum enum

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.