Home > Java > javaTutorial > body text

What are the syntax rules for Java enumeration types?

WBOY
Release: 2024-05-03 12:33:01
Original
1160 people have browsed it

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
}
Copy after login

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);
        }
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!