Home  >  Article  >  Java  >  What are the syntax rules for Java enumeration types?

What are the syntax rules for Java enumeration types?

WBOY
WBOYOriginal
2024-05-03 12:33:011124browse

Java enumeration type is a special constant type used to represent a fixed, known set of constants. Enumeration types are declared using the enum keyword and must declare a public class and inherit java.lang.Enum. Enumeration constants are separated by commas, terminated by a semicolon, and must begin with an uppercase letter. Enumerated types cannot create new instances, but they can have constructors, methods, and fields and are type-safe. Interfaces can also be implemented. For example, the Season enumeration can represent the season of the year and contains constants such as SPRING, SUMMER, AUTUMN, and WINTER, and can be accessed through Season.SPRING, for example.

Java 枚举类型的语法规则是什么?

The syntax rules of Java enumeration types

The enumeration type is a special data type , used to represent a set of fixed, known constants. In Java, enumeration types are declared using the enum keyword.

Syntax:

public enum EnumName {
    CONSTANT1,
    CONSTANT2,
    ...
    CONSTANTn
}

Rules:

  1. The enumeration type must declare a public class that the class inherits from java.lang.Enum.
  2. Enumeration constants are separated by commas and terminated by a semicolon (;).
  3. An enumeration constant is an instance of this enumeration type.
  4. Enumeration constants must start with an uppercase letter.
  5. Enumeration types cannot create new instances.
  6. Enumeration types can have constructors, methods and fields.
  7. Enumeration types are type safe.
  8. Enumeration types can implement interfaces.

Practical case:

public enum Season {
    SPRING,
    SUMMER,
    AUTUMN,
    WINTER
}

public class Main {
    public static void main(String[] args) {
        System.out.println(Season.SPRING);  // 输出:SPRING
        
        for (Season season : Season.values()) {
            System.out.println(season);
        }
    }
}

The above is the detailed content of What are the syntax rules for Java enumeration types?. 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