Master JDK1.5 enumeration types

Source: Internet
Author: User

As a New Keyword introduced by Sun, Enum looks like a special class. It can also have its own variables, define its own methods, and implement one or more interfaces. When declaring an enum type, we should note that the enum type has the following features.

1. It cannot have a public constructor. This ensures that the customer Code cannot create an enum instance.

2. All enumerated values are public, static, and final. Note that this is only for enumeration values. We can define other types of non-enumeration variables like variables defined in common classes. These variables can use any modifier you want.

3. Enum implements the java. lang. Comparable interface by default.

4. Enum overwrites the toString method. Therefore, if we call Color. Blue. toString (), the "Blue" string is returned by default ".

5. Enum provides a valueOf method, which corresponds to the toString method. Calling valueOf ("Blue") will return Color. Blue. Therefore, we need to note this when rewriting the toString method. For example, we should override the valueOf method.

6. Enum also provides the values method, which allows you to easily traverse all enumeration values.

7. enum also has an oridinal method. This method returns the order of the enumerated values in the enumerated classes. This order depends on the order in which the enumerated values are declared. Here, Color. red. ordinal () returns 0.

After learning about these basic features, let's take a look at how to use them.

1. traverse all enumerated values. Once we know the values method, we can easily use the ForEach loop to traverse the enumerated values.

For (Color c: Color. values ())
System. out. println ("find value:" + c );

2. Define methods and variables in enum. For example, we can add a method for Color and return a random Color.

Public enum Color {
Red,
Green,
Blue;

/*
* Define a variable to indicate the number of enumerated values.
* (I'm a bit surprised why sun didn't directly provide the size method for enum ).
*/
Private static int number = Color. values (). length;

/**
* Returns an enumeration value randomly.
@ Return a random enum value.
*/
Public static Color getRandomColor (){
Long random = System. currentTimeMillis () % number;
Switch (int) random ){
Case 0:
Return Color. Red;
Case 1:
Return Color. Green;
Case 2:
Return Color. Blue;
Default: return Color. Red;
}
}
}

It can be seen that there is no difference between defining variables in enumeration types and defining methods and variables in common classes. The only thing to note is that the variables and method definitions must be placed behind the definitions of all enumeration values. Otherwise, the compiler will give an error.

3. Override toString, valueOf Method

We already know that enum provides methods such as toString and valueOf. In many cases, we need to override the default toString method. How can we do this for enum. In fact, this is no different from the toString Method for overwriting a common class.

....
Public String toString (){
Switch (this ){
Case Red:
Return "Color. Red ";
Case Green:
Return "Color. Green ";
Case Blue:
Return "Color. Blue ";
Default:
Return "Unknow Color ";
}
}
....

At this time, we can see that the previous traversal code is used to print out

Color. Red
Color. Green
Color. Blue

Instead

Red
Green
Blue.

We can see that toString is indeed overwritten. Generally, when overwriting toString, we should also overwrite the valueOf method to maintain their consistency.

4. Use constructors

Although enum cannot have a public constructor, we can still define a private constructor, Which is used inside enum. Or use the Color example.

Public enum Color {
Red ("This is Red "),
Green ("This is Green "),
Blue ("This is Blue ");

Private String desc;

Color (String desc ){
This. desc = desc;
}

Public String getDesc (){
Return this. desc;
}

}

Here we provide a description for each color, and then define a constructor to accept this description.

Note that the constructor cannot be public or protected, so that the constructor can only be used internally, and the customer Code cannot create an instance with a new enumerated value. This is also reasonable because we know that the enumerated value is a constant of public static final.

5. Implement specific Interfaces

We already know that enum can define variables and Methods. To implement an interface, it is the same as implementing an interface with a common class. This is not an example here.

6. define the methods of enumeration values.

We can see that we can define some methods for enum. In fact, we can even define methods for each enumerated value. In this way, the previous example of overwriting toString can be rewritten as this.

Public enum Color {
Red {
Public String toString (){
Return "Color. Red ";
}
},
Green {
Public String toString (){
Return "Color. Green ";
}
},
Blue {
Public String toString (){
Return "Color. Blue ";
}
};
}

Logically, this is clearer than the toString method that originally provided a "global.

In general, enum, as a newly defined type, is intended to help programmers write code more easily and easily. I personally feel that it generally does not require too many advanced features of enum, otherwise, it is contrary to the easy-to-understand intention.

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.