Java enum Enum type

Source: Internet
Author: User
Tags protected constructor

An explanation of the enumeration types in Java:

Simple example:

 Public enum color{      red,blue,black,yellow,green  }  

Complex examples (with custom construction methods and types)

 Public enumenumtest {FRANK ("The given name of me"), LIU ("The family name of Me"); PrivateString context; PrivateString GetContext () {return  This. Context; }     PrivateEnumtest (String context) { This. Context =context; }      Public Static voidMain (string[] args) { for(Enumtest name:EnumTest.values ()) {SYSTEM.OUT.PRINTLN (name+" : "+Name.getcontext ());     } System.out.println (EnumTest.FRANK.getDeclaringClass ()); }} 

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. Inheritance, however, is automatically added by the compiler based on the type declaration (public enum).

After we compiled the code, we found that the compiler compiled the enum type into a single bytecode file: Color.class.

Final enumHr.test.Color {//all enumeration values are class static constants&nbsp; Public Static Final enumHr.test.Color RED;&nbsp; Public Static Final enumHr.test.Color BLUE; Public Static Final enumHr.test.Color BLACK; Public Static Final enumHr.test.Color YELLOW; Public Static Final enumHr.test.Color GREEN;Private Static Finalsynthetic hr.test.color[] enum$values; //initialization process, first initialization of all enumerated value objects of the enumeration class&nbsp;Static {       0NewHr.test.Color [1]       3DUP4 LDC <string "RED" > [16]//presses the enumeration value string "RED" into the operand stack6 Iconst_0//pressing an integer value of 0 into the operand stack7 invokespecial Hr.test.Color (java.lang.String,int) [17]//call the private constructor of the color class to create a color object redTen putstatic Hr.test.Color.RED:hr.test.Color [21]//assigns an enumeration object to the static constant red of color.       ......... Enumerating objects blue and so on102return}; //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).  PrivateColor (java.lang.String arg0,intarg1) {     //the protected constructor that invokes the parent class enum creates an enumeration object3 invokespecial java.lang.Enum (java.lang.String,int) [38]};&nbsp; Public Statichr.test.color[] VALUES (); //an abstract method for implementing an Enum class   Public Statichr.test.Color valueOf (java.lang.String arg0);}

Each enumeration in an enumeration type is actually a static instance of declaring an enumeration (or declaring a class) itself.

Because the constructor is an enum of the constructor is protected, so the external is not able to create an instance of the subclass enum can be seen that the constructor is private, so only a few of their own enumeration types to create their own instances.

The characteristics of an enumeration class and its usage:

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.

enumcolor{RED (255,0,0), BLUE (0,0,255), BLACK (0,0,0), YELLOW (255,255,0), GREEN (0,255,0); //constructs an enumeration value, such as red (255,0,0)                PrivateColor (intRvintGvintBV) {                  This. redvalue=RV;  This. greenvalue=GV;  This. bluevalue=BV; }                 PublicString toString () {//ToString () that overrides the parent class enum                return Super. toString () + "(" +redvalue+ "," +greenvalue+ "," +bluevalue+ ")"; }                   Private intRedvalue;//custom data fields, private for encapsulation.                 Private intGreenvalue; Private intBluevalue;}

(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.

 Public Static void Main (String args[]) {        //  color colors=new color (100,200,300);   // wrong           Color color=color.red;           SYSTEM.OUT.PRINTLN (color);   // the ToString () method was called }   

3. All enum classes inherit the Enum method, which we'll describe in detail below.

Enum is constructed by: protected enum (String name, int ordinal)

(0) String name () returns the name of this enumeration constant, which is declared in its enumeration declaration.

(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.

Static <t extends enum<t>> T valueOf (class<t> enumtype, String name)
Color.valueof ("BLUE"); return Result: Color.Blue
(6) Equals () method: Compares references to two enum class objects.

(7) class<e> Getdeclaringclass () returns the Class object that corresponds to the enumeration type of this enumeration constant. When and only if e1.getdeclaringclass () = = E2.getdeclaringclass (), the enumeration types of the two enumeration constants E1 and E2 are the same. (The value returned by the method differs from the value returned by the Object.getclass () method, and the Object.getclass () method is used for enumeration constants of class bodies with specific constants.) )

At the same time, the class overrides the Clone () method of object and the Finalize () method, throws an exception and prevents the destructor method of invoking the enum

4. Enumeration classes can be used in switch statements.

Color color=color.red; Switch (color) {        case RED:System.out.println ("It ' s RED") ;  break;          Case BLUE:System.out.println ("It s Blue");  Break ;          Case BLACK:System.out.println ("It s Blue");  Break ;}

Java enum Enum type

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.