Use and Analysis of Enum in Java

Source: Internet
Author: User
Tags protected constructor

Example:

 
 
  1. public enum EnumTest {  
  2.      FRANK("The given name of me"),  
  3.      LIU("The family name of me");  
  4.      private String context;  
  5.      private String getContext(){  
  6.      return this.context;  
  7.      }  
  8.      private EnumTest(String context){  
  9.      this.context = context;  
  10.      }  
  11.      public static void main(String[] args){  
  12.      for(EnumTest name :EnumTest.values()){  
  13.      System.out.println(name+" : "+name.getContext());  
  14.      }  
  15.      System.out.println(EnumTest.FRANK.getDeclaringClass());  
  16.      }  
  17.  
  18. }  

Java enumeration implementation analysis:

Example:

 
 
  1. public enum Color{    
  2.     RED,BLUE,BLACK,YELLOW,GREEN    
  3. }   

Obviously, enum is similar to a special class. In fact, the type defined by enum is a class. These classes are subclasses of The Enum class in the class library (java. lang. Enum <E> ). They inherit many useful methods in this Enum. After compiling the code, we found that the compiler compiled the enum type into a bytecode file: Color. class.

Color bytecode code:

 
 
  1. Final enum hr. test. Color {
  2. // All enumerated values are static constants.
  3. & Nbsp; public static final enum hr. test. Color RED;
  4. & Nbsp; 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. // Initialize all enumerated value objects of the enumeration class for the first time.
  10. & Nbsp; static {
  11. 0 new hr. test. Color [1]
  12. 3 dup
  13. 4 ldc <String "RED"> [16] // press the enumerated value String "RED" into the operand Stack
  14. 6 iconst_0 // press 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 the Color object RED
  16. 10 putstatic hr. test. Color. RED: hr. test. Color [21] // assign the enumerated object to the static constant RED of Color.
  17. ...... The enumerated object BLUE is the same
  18. 102 return
  19. };
  20. // Private constructor. It is impossible to dynamically create an enumeration Class Object externally (that is, it is impossible to dynamically create an enumeration value ).
  21. Private Color (java. lang. String arg0, int arg1 ){
  22. // Call the protected constructor of the parent class Enum to create an enumerated object
  23. 3 invokespecial java. lang. Enum (java. lang. String, int) [38]
  24. };
  25. & Nbsp;
  26. Public static hr. test. Color [] values ();
  27. // Implement the abstract method of the Enum class
  28. Public static hr. test. Color valueOf (java. lang. String arg0 );
  29. }

The features and usage of enumeration classes defined by enum are described in detail below. The following uses Color as an example)

1. The Color enumeration class is a class which cannot be inherited.

The enumerated values (RED, BLUE...) are static constants of the Color type. We can use the following method to obtain an instance of the Color enumeration class:

 
 
  1. Color c=Color.RED;  

Note: These enumerated values are all public static final, that is, the constant method that we often define. Therefore, it is recommended that all enumeration values in the enumeration class be capitalized.

2. The enumeration class is class. Of course, there are constructors, methods, and data fields in the enumeration type. However, the constructors of enumeration classes are very different:

(1) The constructor is called only when constructing enumeration values.

 
 
  1. Enum Color {
  2. RED (255, 0), BLUE (255,255, 0,255), BLACK (, 0), YELLOW (, 0), GREEN (, 0 );
  3. // Construct enumeration values, such as RED (, 0)
  4. Private Color (int rv, int gv, int bv ){
  5. This. redValue = rv;
  6. This. greenValue = gv;
  7. This. blueValue = bv;
  8. }
  9.  
  10. Public String toString () {// overwrite the toString () of the parent class Enum ()
  11. Return super. toString () + "(" + redValue + "," + greenValue + "," + blueValue + ")";
  12. }
  13. Private int redValue; // custom data domain, private for encapsulation.
  14. Private int greenValue;
  15. Private int blueValue;
  16. }

(2) The constructor can only be private. It is absolutely not allowed to have a public constructor. This prevents external code from creating new enumeration class instances. This is also reasonable because we know that the enumerated value is a constant of public static final.

However, enumeration methods and data domains allow external access.

 
 
  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 is called.
  6. }

3. All enumeration classes inherit the Enum method. The following describes these methods in detail.

(1) ordinal () method: return the order of the enumerated values in the enumerated classes. This order depends on the order in which enumeration values are declared.

 
 
  1. Color. RED. ordinal (); // The returned result is 0.
  2. Color. BLUE. ordinal (); // The returned result is 1.

(2) compareTo () method: Enum implements the java. lang. Comparable interface, so it can be compared to the order of the specified object. CompareTo in Enum returns the order difference between the two enumerated values. Of course, the premise is that the two enumerated values must belong to the same enumeration class, otherwise the ClassCastException () exception will be thrown. (Specific visible source code)

 
 
  1. Color. RED. compareTo (Color. BLUE); // return result-1

(3) values () method: static method. An array containing all enumerated values is returned.

 
 
  1. Color [] colors = Color. values (); for (Color c: colors) {System. out. print (c + ",");}
  2. // Return result: RED, BLUE, black yellow, GREEN,

(4) toString () method: returns the name of the enumerated constant.

 
 
  1. Color c = Color. RED;
  2. System. out. println (c); // The returned result is RED.

(5) valueOf () method: This method corresponds to the toString method, and an enumerated constant of the specified enumeration type with the specified name is returned.

 
 
  1. Color. valueOf ("BLUE"); // return result: Color. BLUE

(6) equals () method: Compares the references of two enumeration class objects.

 
 
  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.

 
 
  1. Color color=Color.RED;  
  2. switch(color){  
  3.         case RED: System.out.println("it's red");break;  
  4.         case BLUE: System.out.println("it's blue");break;  
  5.         case BLACK: System.out.println("it's blue");break;  

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.