A brief talk on enumeration in Java

Source: Internet
Author: User
Tags define abstract response code

Enumerations are enumerated, often used to represent collections that can be explicitly scoped, such as gender, season, week, month, and so on.

The enumeration class appears in JDK 1.5, and before the enumeration class is present, we want to show that several deterministic values are usually represented by constants, such as

     Public Static Final Integer SPRING = 1;      Public Static Final Integer SUMMER = 2;      Public Static Final Integer FALL = 3;      Public Static Final Integer WINTER = 4;

We can use an enumeration class to represent it, which is also the simplest enumeration.

enum season{    spring,summer,fall,winter;}

So what are the advantages of enumerating classes versus defining constants?

Security, we look at the code above to know that the seasons represented by constants are of type Integer, and that the data range of this type is too large, and that using enumerations limits the fields of the data. Enumerations can be understood as a collection of several constants, the data is less likely to change, and the semantics are more explicit after enumeration because the data fields are small.

There are a few things to note about Enum classes:

    1. Enum and class, interface the same position.

    2. Enum classes defined with enum inherit java.lang.Enum by default, rather than inheriting the Object class. An enumeration class can implement one or more interfaces and no longer inherit other classes.

    3. All instances of an enumeration class must be shown on the first line, without the use of the new keyword, without the need to explicitly call the constructor. The public static final decoration is added automatically.

    4. The constructor for an enumeration class can only be private.

On the 4th, I would say that the definition of an enumeration class is a singleton pattern, and a singleton pattern requires the constructor to be privatized and not allow the creation of new objects externally, you think, the function of an enumeration class is to accurately represent different data under the same category. It was created at the time we defined it, so we didn't have to, and we couldn't continue to create new objects outside. Therefore, the constructor needs to be privatized.

The popular point of the enumeration class is the castrated class, we use classes to create objects, and the enumeration classes specify what objects are created when they are defined. You don't have to show the write code creation, but the JVM automatically adds it to you. Let's see what happens after the enum class is deserialized.

You can define properties and methods in an enumeration class.

enumseason{SPRING ("Spring", "Spring"), SUMMER ("Summer", "Summer Good Hot ~"), FALL ("Autumn", "the eyes of a common days"), WINTER ("Winter", "Winter is so cold ~"); //Add the name of an enumeration object    Private FinalString name; //Adding a description of an enumeration object    Private FinalString desc; PrivateSeason (String name,string desc) { This. Name =name;  This. desc =desc; }     PublicString GetName () {returnname; }     PublicString GetDesc () {returndesc; }}

As we can see, there is a private constructor with parameters, so you can assign values directly when you define an enumeration, and the call to create the object is done automatically by the virtual machine, and you can add more properties, and we can use the enumeration object normally.

// gets all the enumeration objects that are returned by the array Season[] values = season.values ();  for + " : " +~~

Implementing an abstract method in an enumeration class

This must be a bit confusing, we know that the class containing the abstract method is an abstract class, then why is the enumeration class not abstract or can contain abstract methods? Let's take a look at the implementation and say why.

enumseason{SPRING ("Spring", "Spring") {@Override PublicSeason Getnextseason () {returnSeason.valueof ("SUMMER"); }},summer ("Summer", "Summer is so hot ~") {@Override PublicSeason Getnextseason () {returnSeason.valueof ("FALL"); }    },        ... Omitted... Omitted... Omitted//defines an abstract method to get the next season     Public AbstractSeason Getnextseason ();}

The test code is as follows

 Public Static void Main (string[] args) {    = Season.SPRING.getNextSeason (). GetName ();     // Summer }

It's not a indefinitely feeling, it's okay, let's go back to the compiler. Look at the internal structure of the enumeration class and you will understand.

Let's take a simple example to see how the enumeration class works. Take one of the simplest enumerations to illustrate the situation.

 Public enum seasonenum {    spring,summer,fall,winter;}

Take a look at the post-compilation code, and the Anti-compilation tool I use is jad.

 Public Final classSeasonenumextendsenum{ Public Staticseasonenum[] VALUES () {return(seasonenum[]) $VALUES. Clone (); }     Public StaticSeasonenum valueOf (String s) {return(Seasonenum) enum.valueof (Seasonenum, s); }    PrivateSeasonenum (String S,inti) {Super(S, i); }     Public Static FinalSeasonenum SPRING;  Public Static FinalSeasonenum SUMMER;  Public Static FinalSeasonenum FALL;  Public Static FinalSeasonenum WINTER; Private Static Finalseasonenum $VALUES []; Static{SPRING=NewSeasonenum ("SPRING", 0); SUMMER=NewSeasonenum ("SUMMER", 1); FALL=NewSeasonenum ("FALL", 2); WINTER=NewSeasonenum ("WINTER", 3); $VALUES= (Newseasonenum[] {SPRING, SUMMER, FALL, WINTER}); }}

You can see that the enumeration class is essentially a singleton final class that inherits the enum, and the enumeration object we define is initialized in a static block of code, and we can see that the implementation of the values method is to return an array of instance objects, that is, an array of enumerated objects, valueOf The method receives a string that returns the enumeration object corresponding to the string and, if not found, an error.

Seeing this we can also understand why we can define abstract methods in enum classes, and we use inner classes to implement abstract methods, each of which implements the corresponding abstract method when it is created. Similarly, enumeration classes can implement interfaces, which are not demonstrated here.

Said so much, but also know the benefits of enumeration, but I have to say that I am in the actual project, the use of enumeration classes is really not much, the following to see what the enumeration class can be useful, in the future there is a need to consider using enumerations to implement.

The switch statement supports enumeration types only starting with JDK 1.5, because this feature is enumerated at this time. Let's take a look at the specific use.

/*** Server Response code*/ Public enumresponsecode {SUCCESS (200, "Access succeeded"), FAIL (404, "Page Not Present"), error (500, "Server Internal Error")); PrivateInteger num; PrivateString desc; Privateresponsecode (Integer num,string desc) { This. num =num;  This. desc =desc; }     PublicInteger Getnum () {returnnum; }     PublicString GetDesc () {returndesc; }    /** Get enumerated object by return code*/     Public Staticresponsecode getbynum (Integer num) { for(Responsecode code:values ()) {if(Code.getnum (). Equals (num)) {returnCode; }        }        return NULL; }}============= Test ===================== Public Static voidMain (string[] args) {Responsecode code= Responsecode.getbynum (200); Switch(code) { CaseSUCCESS:System.out.println (Success);  Break; default:             Break; }    }

In the project I've done, there's only one place to use enumerations to record the value of a dictionary, for example, I write a tool class that records all the dictionary-related data used in the project. Like this.

 Public class Keys {    enum  sex{        male,female;    }     enum state{        success,fail;    }     enum month{     }    enum  week{          }    publicstatic void Main (string[] args) {        Keys.Sex.MALE.name ();    }}

But later, there is a better way to configure the dictionary, create a dictionary class, put all the dictionary data in a table, we use the dictionary class to operate, which is better than using the enumeration above.

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.