Home  >  Article  >  Java  >  How to understand enumeration types in Java

How to understand enumeration types in Java

王林
王林Original
2019-11-13 17:01:253788browse

How to understand enumeration types in Java

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.

How to understand enumeration types in Java

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:How to install javaNext article:How to install java