Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

enum — enumeration type declaration

enum — enumeration type declaration: enum declares an enum class with a finite set of instances; each constant may take arguments and have a constant-specific class body that overrides behavior.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

enum

enum declares an enum class with a finite set of instances; each constant may take arguments and have a constant-specific class body that overrides behavior.

Use fields, a private constructor, and abstract methods implemented in each constant-specific class body when constants represent distinct strategies.

Do not persist ordinal as data or protocol, and do not depend on names that refactoring may change; valueOf requires an exact case-sensitive name.

A constant with a constant-specific class body has an anonymous subclass, so getClass may differ from the enum type; a switch may need handling for a new constant.

Two constant-specific class bodies implement apply as addition and multiplication, yielding 5 and 6; true confirms PLUS has an anonymous class.

Examples

public class Main {
    enum Operation {
        PLUS {
            @Override int apply(int left, int right) { return left + right; }
        },
        TIMES {
            @Override int apply(int left, int right) { return left * right; }
        };
        abstract int apply(int left, int right);
    }

    public static void main(String[] args) {
        System.out.println(Operation.PLUS.apply(2, 3));
        System.out.println(Operation.TIMES.apply(2, 3));
        System.out.println(Operation.PLUS.getClass() != Operation.class);
    }
}

Result

5
6
true

Two constant-specific class bodies implement apply as addition and multiplication, yielding 5 and 6; true confirms PLUS has an anonymous class.

Sources