Java record-79-enumeration (Enums)
Enumeration (Enums) JDK1.5 adds a brand new "class"-Enumeration type. Therefore, JDK1.5 introduces a new keyword enum. In this way, we can define an enumeration type Public enum Color {Red, White, Blue} and then use Color myColor = Color. red; The Enumeration type also provides two useful static methods: values () and valueOf (). We can easily use them, for example: for (Color c: Color. values () System. out. println (c); when defining enumeration types, it is essentially defining a category, but many details are completed by the compiler. To some extent, the enum keyword acts like a class or interface. When you use "enum" to define the enumeration type, the type you defined actually inherits from java. lang. enum type, and each enumeration member is actually an Instance of the enumeration type you define. They are all preset as final, so you cannot change them. They are also static members, therefore, you can use them directly by type names. Of course, the most important of them are public. In other words, after defining an enumeration type, you can determine the number of instances of this enumeration type at the time of compilation. During the runtime, we can no longer use this enumeration type to create new instances. These instances have been completely determined during compilation. Simple definition and use of enumeration:
// Definition of enumeration public enum Color {Red, White, Blue} // public class ColorTest {public static void main (String [] args) {Color myColor = Color. red; System. out. println (myColor); for (Color c: Color. values () {System. out. println (c );}}}
Enumeration common scenarios:
Public class EnumTest {public static void doOp (OpConstant op) {switch (op) {case TURN_LEFT: System. out. println ("Turn left"); break; case TURN_RIGHT: System. out. println ("Turn right"); break; case SHOOT: System. out. println ("shot"); break;} public static void main (String [] args) {doOp (OpConstant. SHOOT) ;}} enum OpConstant {TURN_LEFT, TURN_RIGHT, SHOOT}