Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Enum constant-specific class body

In Java SE 21, an `enum` constant can pass arguments to the enum constructor and have its own class body to define its behavior.

Version: Java SE 21

Syntax

EnumConstant ::= Annotation* Identifier [ '(' [ ArgumentList ] ')' ] [ ClassBody ]
ArgumentList ::= Expression ( ',' Expression )*

Here [ ... ] means optional, * means zero or more, and quoted punctuation is literal. ClassBody is the constant's { ... } body.

In RED(30) { ... }, the parentheses hold constructor arguments, and the braces enclose the enum constant-specific class body. This optional body implicitly declares an anonymous, direct final subclass of Signal. It cannot declare constructors or abstract methods.

Separate constants with commas. If declarations follow the constant list in the enum body, use a semicolon ; to separate them from the list. During class initialization, each constant's arguments go to the enum constructor selected by normal overload resolution. Omitting the parentheses means an empty argument list. An enum constructor with no access modifier is private. Here, Signal(int seconds) stores the argument in the private final int seconds instance field.

If an enum has an abstract method, it must have at least one constant, and every constant must supply a concrete implementation in its own body. A missing implementation is a compile-time error. @Override lets the compiler check that the method really overrides another method. A call to signal.next() selects the implementation for the constant that signal refers to. An instance method declared in a constant body can be called from outside the enclosing enum class only if it overrides an accessible method of that enum.

Examples

public class Main {
    enum Signal {
        RED(30) {
            @Override
            Signal next() { return GREEN; }
        },
        GREEN(25) {
            @Override
            Signal next() { return YELLOW; }
        },
        YELLOW(5) {
            @Override
            Signal next() { return RED; }
        };

        private final int seconds;

        private Signal(int seconds) {
            this.seconds = seconds;
        }

        int seconds() {
            return seconds;
        }

        abstract Signal next();
    }

    public static void main(String[] args) {
        for (Signal signal : Signal.values()) {
            System.out.println(signal.name() + " (" + signal.seconds()
                    + " s) -> " + signal.next().name());
        }
    }
}

Result

RED (30 s) -> GREEN
GREEN (25 s) -> YELLOW
YELLOW (5 s) -> RED

`seconds()` returns the duration stored for the current signal, while `next()` returns the next existing constant. `Signal.values()` returns the constants in declaration order.

Related lessons

  • Java · Lesson 9 · Intermediate · Version: 2

Sources