Home > Back-end > In JAVA enumeration (why the output is the name of the enumeration values rather than address value)
In JAVA enumeration (why the output is the name of the enumeration values rather than address value)
Time:05-22
Public class Test { Enum Color { RED, GREEN, BLUE; } }
//execution output Public static void main (String [] args) { Color c1=Color. RED; System. The out. Println (c1); } //output is the result of the RED //why output is RED, the address values should not be RED?
CodePudding user response:
1. All the enumeration is inherited from an Enum
2. Enum override the toString method
public String toString () { return name; }
CodePudding user response:
Because enumerated types the resulting class files after the decompiled code is Public final class Color extends Enum { Public static Color [] values () { Return (Color []) $VALUES. The clone (); }
Public static Color the valueOf (String name) { Return (Color) Enum. The valueOf (Color, name); }
Private Color (String s, int I) { Super (s, I); }
Public static final Color RED; Public static final Color GREEN; Public static final Color BLUE. Private static final Color $VALUES [];
The static { RED=new Color (" RED ", 0); GREEN=new Color (" GREEN ", 1); BLUE=new Color (" BLUE ", 2); $VALUES=(new Color [] { RED, GREEN, BLUE }); } } The default toString method and enumeration class is such a Public abstract class Enum Implements Comparable , the Serializable { //omit other code Public String toString () { return name; } } And the name is private constructor Private Color (String s, int I) { Super (s, I); } the s So, summarized as follows: each enumeration class finally after decompiling is inherited an enum, at the same time more private constructor Private Color (String s, int I) { Super (s, I); } and attribute name, and ultimately through the console output is this name, which is defined in the enumeration class each enumeration value