Java Enumeration details

Source: Internet
Author: User

1. Before the enumeration, we need some constants, for example, we want to use some constants to replace the order of several states, such as the orders have not been paid, the payment has not been shipped, shipped unconfirmed receipts, received non-evaluation, has been evaluated. We will define a class to load constants, such as:

 PackageCom.xdx.learn; Public classOrderconstant { Public Static Final intUnpay=1;//not paid     Public Static Final intundeliver=2;//not shipped     Public Static Final intunreceive=3;//Goods not received     Public Static Final intuncomment=4;//not evaluated}

When called elsewhere, we go directly through the orderconstant. Unpay can get to this constant.

2. With the enumeration type, we will write the code like this.

Creates a new enumeration class.

  

 Public enumorderenum {unpay ("Unpay", 1), Undeliver ("Undeliver", 2), unreceive ("Unreceive", 3), uncomment ("Uncomment", 4); PrivateString Key; Private intvalue; PrivateOrderenum (String Key,intvalue) {         This. key=key;  This. value=value; }         PublicString GetKey () {returnkey; }     Public voidSetkey (String key) { This. Key =key; }     Public intGetValue () {returnvalue; }     Public voidSetValue (intvalue) {         This. Value =value; }     Public Static voidMain (String args[]) {System.out.println (OrderEnum.UNPAY.getKey ());    System.out.println (OrderEnum.UNPAY.getValue ()); }}

Above is an enumeration class, which has the following characteristics.

(1) It is not modified by class, but by the enum keyword. But to be sure, it's essentially a class.

(2) Its constructor cannot be modified with public, only with private, that is, we cannot instantiate an object of an enumeration class externally. What does that make you think of? is not a singleton mode.

(3)Unpay ("Unpay", 1), Undeliver ("Undeliver", 2), unreceive ("Unreceive", 3), uncomment ("Uncomment", 4); These are all objects of the enumeration class (they are all orderenum types) and exist in the enumeration class in the form of a member variable of a static constant. In fact, they are public static final type, so we can use the class name outside of the class. member variables, such as Orderenum.unpay, are accessed.

(4) Once you have defined an enumeration class, you must also create an instance of it, which is the instance of Unpay ("Unpay", 1) above. The creation of the instance is simplified, only the constructor needs to be called, and the new keyword is not required.

In fact, as I understand it, the above enumeration classes can be replaced by the following classes.

  

 PackageCom.xdx.learn; Public classOrdermulti {PrivateString Key; Private intvalue; PrivateOrdermulti (String Key,intvalue) {         This. key=key;  This. value=value; }         PublicString GetKey () {returnkey; }     Public voidSetkey (String key) { This. Key =key; }     Public intGetValue () {returnvalue; }     Public voidSetValue (intvalue) {         This. Value =value; }     Public Static FinalOrdermulti unpay=NewOrdermulti ("Unpay", 1);  Public Static FinalOrdermulti undeliver=NewOrdermulti ("Undeliver", 2);  Public Static FinalOrdermulti unreceive=NewOrdermulti ("Unreceive", 3);  Public Static FinalOrdermulti uncomment=NewOrdermulti ("Uncomment", 4);  Public Static voidMain (String args[]) {System.out.println (OrderMulti.UNPAY.getKey ());    System.out.println (OrderMulti.UNPAY.getValue ()); }}

Yes, the enumeration class is equivalent to a Java class with multiple cases (multiple patterns). Just Java syntax helps us with these explicit instantiation operations and is represented in a simpler syntax. It becomes an enum.

3. In fact, the enumeration class is the subclass of the Enum class, to check the JDK source code, found that the enum is an abstract generic class, which is defined as public abstract class Enum<e extends enum<e>>
Implements Comparable<e>, Serializable. In fact, the Orderenum class mentioned above can be understood as such a class.

public class Orderenum extends Enum<orderenum> yes, the generic type argument is the enumeration class itself.

But when you actually type in the above class in eclipse, you will find an error, because the Enum class is not inheritable, and the wrong hint is that the type Orderenum may not subclass Enum<a> explicitly. You cannot explicitly inherit an enum. At compile time, the JDK rejects a class to inherit the enum, for what reason, how to implement, I do not know. All we need to know is the enum-decorated class, whose parent is the enum.

In this case, enum-modified classes are not allowed to inherit other classes, because Java is single-inheritance. Of course, the Enum class can be extended by implementing an interface.

Because the enumeration class inherits from the enum, some of the methods within the enum can also be used. Look at the following code, using a few more commonly used methods.

  

     Public Static voidMain (String args[]) {System.out.println (OrderEnum.UNPAY.getKey ());        System.out.println (OrderEnum.UNPAY.getValue ()); //The name () method gets the names of the instance of the enumeration classSystem.out.println (OrderEnum.UNPAY.name ()); //The ordinal () method gets the sort of the enumeration class instance in all instances, starting with 0. System.out.println (OrderEnum.UNPAY.ordinal ()); //The CompareTo () method compares the ordering of two enumeration instances, which can be considered to be the value of the former ordinal-the ordinal of the latter. System.out.println (OrderEnum.UNPAY.compareTo (orderenum.undeliver));        System.out.println (OrderEnum.UNRECEIVE.compareTo (orderenum.undeliver));        System.out.println (OrderEnum.UNCOMMENT.compareTo (orderenum.undeliver)); //gets the class of the enumeration objectSystem.out.println (OrderEnum.UNPAY.getDeclaringClass ()); //Verify that the parent class of the enumeration class is indeed an enumSystem.out.println (OrderEnum.UNPAY.getDeclaringClass (). Getsuperclass ());        System.out.println (OrderEnum.UNPAY.equals (orderenum.uncomment)); //iterating through an instance in an enumeration class         for(Orderenum orderenum:OrderEnum.values ()) {System.out.println (Orderenum.getkey ()); }    }

The result of the above code is:

Unpay
1
Unpay
0
-1
1
2
Class Com.xdx.learn.OrderEnum
Class Java.lang.Enum
False
Unpay
Undeliver

Unreceive
Uncomment

4. As long as the enumeration is understood as a class that implements multiple patterns, there is no difficulty in applying them. But some people will ask, I use the first way, that is, directly using a public static final int Unpay=1. Such a constant. Is it possible to implement the functionality required by enumerations? Why do you have to go through the trouble of defining an enumeration class? I think it is based on the following considerations.

(1) First, the class name of the enumeration class can have some indication, for example, we give an enumeration class named week, we can know that it should be representative of the week, and before the enumeration, we use the constant container class, often only define a class, named similar to the constant class, It's hard to go inside and find the constant value.

(2) When the enumeration is used as the formal parameter of a function, it can play a limited role. For example, I have a function that I can define as void func (int x) and accept some constant values. I can also define a form such as void func (Orderenum orderenum). The advantage of the latter is that it restricts the arguments passed in to an instance of the enumeration class, while the former can pass in any integral type.

  

Java Enumeration details

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.