thecodex.expert · The Codex Family of Knowledge
Java

Enums

A Java enum can have constructors, fields, and methods — including a different method implementation for each individual constant. It is a real class, not just a labeled set of integers.

Java 21 LTS Enums can have methods Last verified:
Canonical Definition

enum defines a type restricted to a fixed set of named instances, each one a genuine singleton object of that type. Unlike C's plain-integer enums, a Java enum can declare a constructor (called once per constant, at class-loading time), instance fields, and methods — and each individual constant can even provide its own override of a method, using an anonymous-class-like body.

A basic enum, and switch over it

Every enum automatically gets values() (an array of every constant), name(), and ordinal() (its declaration position) for free — no need to declare any of these yourself.

JavaDay.java
public enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

Day today = Day.WEDNESDAY;
String type = switch (today) {
    case SATURDAY, SUNDAY -> "Weekend";
    default -> "Weekday";
};

for (Day d : Day.values()) {   // values(): every constant, in declaration order
    System.out.println(d.ordinal() + ": " + d.name());
}

Enums with fields and a constructor

The constructor runs exactly once per constant, when the enum class is first loaded — each constant is genuinely a distinct singleton object carrying its own field values.

JavaPlanet.java
public enum Planet {
    MERCURY(3.303e+23, 2.4397e6),
    VENUS(4.869e+24, 6.0518e6),
    EARTH(5.976e+24, 6.37814e6);

    private final double mass;    // kg
    private final double radius;  // meters

    Planet(double mass, double radius) {   // constructor: runs once per constant
        this.mass = mass;
        this.radius = radius;
    }

    public double surfaceGravity() {
        final double G = 6.67300E-11;
        return G * mass / (radius * radius);
    }
}

System.out.println(Planet.EARTH.surfaceGravity());

Per-constant method bodies

Each constant can override the abstract method with its own body — a genuinely powerful pattern for encoding a small, fixed set of type-specific behaviors without a separate class hierarchy.

JavaOperation.java
public enum Operation {
    ADD { public int apply(int a, int b) { return a + b; } },
    SUBTRACT { public int apply(int a, int b) { return a - b; } },
    MULTIPLY { public int apply(int a, int b) { return a * b; } };

    public abstract int apply(int a, int b);   // each constant provides its own body above
}

System.out.println(Operation.MULTIPLY.apply(3, 4));   // 12

Sources

1
Oracle. The Java Tutorials, "Enum Types," docs.oracle.com/javase/tutorial/java/javaOO/enum.html.