What is an enumeration type?
An enumeration is a collection of named integer constants used to declare a set of constants with identifiers. Enumerations are very common in daily life. For example, a person's gender can only be "male" or "female", a week can only be one of the seven days, etc. Like this, when a variable has several fixed possible values, it can be defined as an enumeration type.
Declaring an enumeration
You must use the enum keyword when declaring an enumeration, and then define the name, accessibility, base type, members, etc. of the enumeration. The syntax of the enumeration declaration is as follows:
enum-modifiers enum enumname:enum-base { enum-body, }
enum-modifiers
: Indicates the modifiers of the enumeration, mainly including public, private and internal;
enumname
: Represents the declared enumeration name;
enum-base
: Represents the base type;
enum- body
: Represents a member of the enumeration, which is a named constant of the enumeration type.
Enumeration class
Every enumeration in Java inherits from the java.lang.Enum class. When defining an enumeration type, each enumeration type member can be regarded as an instance of the Enum class. These enumeration members are modified by final, public, and static by default. When using enumeration type members, use the enumeration directly. Just call the member by name.
All enumeration instances can call the methods of the Enum class. Common methods are shown in Table 1.
Instance:
By calling the values() method of the enumeration type instance, all members of the enumeration can be returned in the form of an array, or through the Method to obtain the members of an enumeration type.
The following example creates an enumeration type Signal containing 3 members, and then calls the values() method to output these members.
enum Signal { //定义一个枚举类型 GREEN,YELLOW,RED; } public static void main(String[] args) { for(int i=0;i<Signal.values().length;i++) { System.out.println("枚举成员:"+Signal.values()[i]); } }
Output result:
枚举成员:GREEN 枚举成员:YELLOW 枚举成员:RED
Recommended tutorial: Java tutorial
The above is the detailed content of How to understand enumeration types in Java. For more information, please follow other related articles on the PHP Chinese website!