The use and analysis of enum in Java

Source: Internet
Author: User
Tags protected constructor

Example:

public enum Enumtest {FRANK ("The given name of Me"), LIU ("The family name of Me");     Private String context;     Private String GetContext () {return this.context;     } Private Enumtest (String context) {This.context = context; public static void Main (string[] args) {for (Enumtest name:EnumTest.values ()) {System.out.println (name+ "):      "+name.getcontext ());     } System.out.println (EnumTest.FRANK.getDeclaringClass ()); }

}

Analysis of enumeration implementations in Java:

Example:

    1. public enum color{
    2. Red,blue,black,yellow,green
    3. }

Obviously, the enum is very much like a special class, in fact the type of the enum declaration definition is one. These classes are subclasses of the Enum class in the class library (java.lang.enum<e>). They inherit many of the useful methods in this enum. After we compiled the code, we found that the compiler compiled the enum type into a single bytecode file: Color.class.

Color Bytecode Code
  1. Final enum Hr.test.Color {
  2. All enumeration values are class static constants
  3. public static final enum Hr.test.Color RED;
  4. public static final enum Hr.test.Color BLUE;
  5. public static final enum Hr.test.Color BLACK;
  6. public static final enum Hr.test.Color YELLOW;
  7. public static final enum Hr.test.Color GREEN;
  8. private static final synthetic hr.test.color[] enum$values;
  9. Initialization process, first initialization of all enumerated value objects of the enumeration class
  10. static {
  11. 0 new Hr.test.Color [1]
  12. 3 DUP
  13. 4 LDC <string "Red" > [16]//Push the enumeration value string "Red" into the operand stack
  14. 6 ICONST_0//Pressing the integer value 0 into the operand stack
  15. 7 invokespecial Hr.test.Color (java.lang.String, int) [17]//Call the private constructor of the color class to create a color object red
  16. Putstatic Hr.test.Color.RED:hr.test.Color [21]//Assign the enumeration object to the static constant RED of Color.
  17. ......... Enumerating objects blue and so on
  18. 102 return
  19. };
  20. Private constructors, it is not possible to dynamically create an enumeration class object (that is, it is not possible to dynamically create an enumeration value).
  21. Private Color (java.lang.String arg0, int arg1) {
  22. The protected constructor that invokes the parent class enum creates an enumeration object
  23. 3 invokespecial java.lang.Enum (java.lang.String, int) [38]
  24. };
  25. public static hr.test.color[] values ();
  26. An abstract method for implementing an Enum class
  27. public static Hr.test.Color valueOf (java.lang.String arg0);
  28. }

The following is a detailed description of the characteristics and usages of enum classes defined by the enum. (color example is used later)

1, the Color enumeration class is class, and is a final class that cannot be inherited. Its enumeration value (Red,blue ...) are all class static constants of the color type, we can get an instance of the color enum class in the following way:
Color c=color.red;
Note: These enumeration values are public static final, which is the constant way that we often define, so the enumeration values in the enumeration class are best capitalized.

2, the enumeration class is class, of course, there are constructors, methods and data fields in the enumeration type. However, the constructors of enum classes are very different:
(1) The constructor is called only when the enumeration value is constructed.

Java code
  1. Enum color{
  2. RED (255,0,0), BLUE (0,0,255), BLACK (0,0,0), YELLOW (255,255,0), GREEN (0,255,0);
  3. Constructs an enumeration value, such as Red (255,0,0)
  4. Private Color (int rv,int Gv,int BV) {
  5. THIS.REDVALUE=RV;
  6. THIS.GREENVALUE=GV;
  7. THIS.BLUEVALUE=BV;
  8. }
  9. Public String ToString () {//Overrides toString () of the parent enum
  10. return super.tostring () + "(" +redvalue+ "," +greenvalue+ "," +bluevalue+ ")";
  11. }
  12. private int redvalue; Custom data fields, private for encapsulation.
  13. private int greenvalue;
  14. private int bluevalue;
  15. }

(2) The constructor can only be private, and there is absolutely no public constructor allowed. This guarantees that external code cannot newly construct an instance of the enumeration class. This is perfectly reasonable, because we know that the enumeration value is a constant of public static final. However, the methods and data fields of the enumeration class can allow external access.

Java code
    1. public static void Main (String args[])
    2. {
    3. Color Colors=new color (100,200,300); Wrong
    4. Color color=color.red;
    5. SYSTEM.OUT.PRINTLN (color); The ToString () method was called
    6. }

3. All enum classes inherit the Enum method, which we'll describe in detail below.
(1) ordinal () method: Returns the order of enumeration values in the enumeration class. This order depends on the order in which the enumeration values are declared.
Color.RED.ordinal (); Results returned: 0
Color.BLUE.ordinal (); Results returned: 1
(2) CompareTo () method: Enum implements the Java.lang.Comparable interface, so you can compare the order of objects like the specified object. The CompareTo in the enum returns the difference in order of the two enumeration values. Of course, the premise is that two enumeration values must belong to the same enumeration class, otherwise a classcastexception () exception will be thrown. (Visible source code)
Color.RED.compareTo (Color.Blue); return result-1
(3) The values () method: A static method that returns an array that contains all the enumeration values.
Color[] Colors=color.values ();
for (Color c:colors) {
System.out.print (c+ ",");
}//return Result: Red,blue,black Yellow,green,
(4) ToString () method: Returns the name of the enumeration constant.
Color c=color.red;
System.out.println (c);//return Result: RED
(5) ValueOf () Method: This method is relative to the ToString method and returns an enumeration constant of the specified enumeration type with the specified name.
Color.valueof ("BLUE"); return Result: Color.Blue
(6) Equals () method: Compares references to two enum class objects.

Java code
    1. JDK Source code:
    2. Public final Boolean equals (Object other) {
    3. return this==other;
    4. }


4. Enumeration classes can be used in switch statements.

Java code
    1. Color color=color.red;
    2. switch (color) {
    3. Case RED:System.out.println ("It ' s RED");
    4. Case BLUE:System.out.println ("It s BLUE");
    5. Case BLACK:System.out.println ("It s Blue");
    6. }

The use and analysis of enum in Java

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.