Enum class Enum was introduced by JDK1.5, which was preceded by the public static final int Enum_value instead of the enumeration class. Enum class Enum is a special class that inherits the class Java.lang.Enum by default. Like other ordinary classes, an enum can have member variables, methods, constructors, or one or more interfaces, the difference being:
- If there is a constructor, it must be decorated with private.
- An enumeration class cannot derive subclasses.
- All instances of an enumeration class must display the definition on the first line. The system automatically adds public static final adornments to these instances without requiring the programmer to display the definitions.
- The enumeration class provides the values () method by default, which makes it easy to traverse all enumerated values
Methods in Enum (the method provided by the enum):
Public final int compareTo (E o) Compares enumeration values of the same type
Public final int ordinal () returns the index value of the enumeration, with the first enumeration value starting from zero.
Public final String name () returns the enumeration instance name
Public String toString () returns the enumeration yield name
Traffic light Example
Public enumTrafficLight {RED ("Red"), YELLOW ("Yellow"), GREEN ("Green");PrivateString name;Private TrafficLight(String name) { This. name = name; } PublicStringGetName() {returnName } Public void Jude(TrafficLight Light) {Switch(light) { CaseRED:System.out.println ("Stop"); Break; CaseYELLOW:System.out.println ("Go"); Break; CaseGREEN:System.out.println ("Wait"); Break;default: Break; } } Public Static void Main(string[] args) { for(TrafficLight e:trafficlight.values ()) {System.out.println (E.name ()); } }}
The Java Enumeration class enum explanation