An enumeration is a special data type. The reason why it is special is that it is a class type but has some more special constraints than a type. However, the existence of these constraints also creates an enumeration. Type simplicity, safety, and convenience.
To create an enumeration type, you must use the enum keyword, which implies that the types created are all java.lang. A subclass of the Enum class (java.lang.Enum is an abstract class).
The enumeration type conforms to the general pattern Class Enum
Each value of the enumeration type is mapped to the protected Enum(String name, int ordinal) constructor, where the name of each value are converted to a string, and the ordinal setting represents the order in which this setting is created.
Use of enumeration:
Create an enumeration class: EnumTest
public enum EnumTest { //星期一,星期二,星期三,星期四,星期五,星期六 MON(1), TUE(2),WED(3),THU(4),FRI(5),SAT(6){ public boolean isRest(){ return true; } }, //星期日 SUN(0){ public boolean isRest(){ return true; } }; private int value; private EnumTest(int value){ this.value=value; } public int getValue(){ return value; } public boolean isRest(){ return false; } }
Use EnumTest enumeration class:
public class EnumMain { public static void main(String[] args) { for (EnumTest enumTest : EnumTest.values()) { System.out.println(enumTest + ":" + enumTest.getValue()); } System.out.println("---------------我是分割线------------"); EnumTest test = EnumTest.SAT; switch (test) { case MON: System.out.println("今天是星期一"); break; case TUE: System.out.println("今天是星期二"); break; case WED: System.out.println("今天是星期三"); break; case THU: System.out.println("今天是星期四"); break; case FRI: System.out.println("今天是星期五"); break; case SAT: System.out.println("今天是星期六"); break; case SUN: System.out.println("今天是星期日"); break; default: System.out.println(test); break; } } }
The above is the detailed content of What exactly are enumerations in java?. For more information, please follow other related articles on the PHP Chinese website!