Lesson 31 / 38

Enums

Model a fixed set of constants as a Java enum that carries fields, a constructor and methods, and switches cleanly without magic numbers.

More than constants

An enum is a fixed set of instances. It can have fields, a constructor, and methods, and works cleanly in switch.

enum Planet {
    EARTH(9.81), MARS(3.71);
    private final double gravity;
    Planet(double g) { this.gravity = g; }
    double weight(double mass) { return mass * gravity; }
}

Planet.MARS.weight(70);   // 259.7

Per-constant bodies

Each constant can override an abstract method with its own body — a clean alternative to a switch full of behaviour.

enum Op {
    ADD { public int apply(int a, int b) { return a + b; } },
    MUL { public int apply(int a, int b) { return a * b; } };

    public abstract int apply(int a, int b);
}

Op.ADD.apply(2, 3);   // 5
Op.MUL.apply(2, 3);   // 6

values(), valueOf(), ordinal()

Every enum gets values() (an array of all constants, in declaration order), valueOf("NAME") (parses a name, throws if unknown), and ordinal() (its position, starting at 0). Avoid persisting ordinal() — reordering constants silently breaks it; store name() instead.