Lesson · Enums
Enums: a fixed set of objects, created once
16 min readEnums
An enum is a class with a closed list of instances: each constant is a singleton created at class initialisation, carrying whatever data and behaviour the declaration gives it. Never persist its ordinal.
The int constant that accepted 99
Status codes as int constants work until a wrong value sneaks through the type system's fingers:
static final int OPEN = 1; static final int CLOSED = 2; void setStatus(int status) { ... } setStatus(99); // compiles: ints are ints System.out.println(OPEN); // 1: logs show numbers, not meaning enum Status { OPEN, CLOSED } void setStatus(Status status) { ... } // setStatus(99); // does not compile: the set has four walls
Predict: what does System.out.println(Status.OPEN) print? OPEN, its own name. An enum is not a fancy int: it is a class whose instances are a fixed, known list, each with a real identity, readable text, and a compiler that refuses everything else.
What the compiler writes for you
Declaring enum Status { OPEN, CLOSED } produces a full class. The members it carries:
| Member | Does | Detail worth knowing |
|---|---|---|
values() | Returns every constant, in declaration order | A fresh array each call; iterate it, do not compare it |
valueOf("OPEN") | Looks a constant up by exact name | Missing name throws IllegalArgumentException |
name() | The exact identifier as written | Stable text for logs and persistence |
ordinal() | The 0-based position | A position, not a meaning: never persist it |
compareTo | Orders by ordinal | Useful for EnumSet iteration, hazardous for logic |
equals / hashCode | Identity, because instances are singletons | == is correct and idiomatic for enums |
- One instance per constant, forever: enums are created by the class initialisation machinery, so two references to
Status.OPENare always the same object. - The set is closed: the constructor is implicitly private; nobody outside can add members, which makes switch statements over enums exhaustive (the compiler checks).
- Enums are classes: they can have fields, methods and constructors; what they cannot do is extend another class, because every enum already extends
java.lang.Enum.
`==` beats `equals` here, and it is not a shortcut. With one instance per constant, identity comparison is exact, null-safe (null is never equal) and faster; it also reads as what you mean.
Constants with data and behaviour
Constants are objects, so they can be constructed with arguments and answer questions themselves:
enum Status { OPEN("accepting", 1), CLOSED("done", 2); final String label; final int level; Status(String label, int level) { // runs once per constant this.label = label; this.level = level; } }
- The constructor signature sits in the constant list: each constant passes its own arguments.
- Constructors run once per constant at class initialisation, in declaration order, the first time the enum is touched.
- Fields can be final: each constant is built once and never rebuilt, so
CLOSED.labelis a fact, not a lookup. - A constant can even override behaviour in its own body (constant-specific bodies), when
PLUSandMINUSeach implementapplydifferently.
The enum initialisation is the class initialisation lesson in miniature. Constants are static fields; their constructors run in order at first use, and the verified order (all constructors, then the calling code) is worth watching once in the trace above.
The guest list · constants as built objects
Current statement
Output
nothing yet
The declaration becomes a final class with two static final instances and a private constructor. Nothing has been created yet: that waits for the first touch.
Ordinal, EnumSet and EnumMap
Three follow-ups the implicit methods imply:
- Never persist `ordinal()`: it is a position in today's source file. Reorder the constants (a harmless-looking edit) and every stored 0 or 1 means something else. Persist
name()or a stablecodefield instead. - `EnumSet` and `EnumMap` exist for enums: built on the constants' fixed count, they are far smaller and faster than
HashSet/HashMap(a bit-vector and an array, conceptually), and they iterate in declaration order. - The enum singleton:
enum Registry { INSTANCE; }is the irreducible thread-safe, serialisation-safe singleton: the class machinery creates the one instance, and deserialisation cannot make a second.
Positions are for iteration; names are for storage. The rule is one line long and prevents a whole genre of migration bugs: what leaves your program (a database column, a wire format) must be the constant's name or an explicit code, never its ordinal.
The enum playbook
Replacing constants and modelling fixed sets, in order:
- Whenever a set of values is fixed and known (states, modes, kinds), reach for an enum, not ints or strings.
- Attach the data each constant needs through constructor fields; put shared behaviour in methods on the enum.
- Use
switchover the enum for per-constant actions; the compiler's exhaustiveness checks keep it honest as the set grows. - Compare with
==; reserveequalsfor generic Collection code that must call it. - Persist
name()or a dedicated code field; keepordinal()for iteration-order concerns only. - For sets and maps keyed by an enum, use
EnumSetandEnumMapby default.
A closed set of objects, each one real. That sentence replaces int constants, string constants, boolean flags stacked together, and the class-load singleton, all of which enums do better.
An enum is a class with a guest list
Each constant is a singleton instance created at class initialisation, so == is exact, switch is exhaustive, and constants can carry fields and behaviour like any object. Free members (values, valueOf, name, ordinal) come with the declaration; persist names, never ordinals, and prefer EnumSet/EnumMap when the keys are enum members.
Interview angles
What exactly is an enum under the hood?+
A final class extending java.lang.Enum whose declared constants are public static final singleton instances, created by the class initialisation machinery with an implicitly private constructor.
That shape explains every behaviour: identity comparison, switch support, exhaustive checks, serialisation safety, and why enums cannot extend anything else (the single-inheritance slot is taken by Enum).
enum Status { OPEN, CLOSED } // compiles to a class with two singletons and no way to make a third
Common misconception: That enums are glorified constants. They are classes: fields, methods, constructors and per-constant behaviour are all on the table.
Follow-up: Why can an enum not extend another class?
Why is == the right comparison for enums?+
Because each constant exists exactly once: identity is the whole meaning of the comparison, and no equals override can disagree with it.
== is null-safe (a null enum fails cleanly) and avoids an equals call; the JDK style guides and the compiler itself treat enum identity as exact. equals still works and remains correct for generic code that must use it.
status == Status.OPEN; // exact and idiomatic Status.OPEN.equals(status); // correct, but the long way around
Common misconception: That 'always use equals' applies here too. That rule guards against object equality semantics; enums have none to guard against.
Follow-up: Where does equals remain the right call even for enums?
Why is persisting ordinal() a bug waiting to happen?+
Because it stores a position in the current source file: any later reordering (or insertion in the middle) silently changes what every stored number means.
The same applies to wiring ordinals into calculations; the position is metadata for iteration, not a stable identity. Persist name() (or an explicit code field) so the stored value keeps its meaning across releases.
// stored: 1 // statuses reordered next release: // OPEN, CLOSED // CLOSED, PENDING, OPEN -> the stored 1 means something else
Common misconception: That ordinals are stable because the enum looks stable. Source files evolve; databases outlive them.
Follow-up: What does valueOf throw when a stored name no longer exists?
What are constant-specific bodies for?+
Giving each constant its own implementation of a shared abstract method, so behaviour lives beside the data it depends on.
Operation.PLUS and Operation.MINUS each override apply, and op.apply(2, 3) dispatches like any override. It replaces switch-based helpers with polymorphism when each constant's behaviour deserves its own code block.
enum Operation { PLUS { @Override double apply(double a, double b) { return a + b; } }, MINUS { @Override double apply(double a, double b) { return a - b; } }; abstract double apply(double a, double b); }
Common misconception: That constant bodies replace methods on the enum. They specialise them; shared behaviour still belongs in the enum's own methods.
Follow-up: When is a plain switch clearer than constant-specific bodies?
When do you use EnumSet and EnumMap?+
Whenever a set or map is keyed by an enum: they are specialised structures (conceptually a bit-vector and an array) that are dramatically smaller and faster than HashSet and HashMap.
They also know all the constants, which gives declaration-order iteration and cheap bulk operations like EnumSet.allOf(Status.class) or complement. For any 'flags' use case, EnumSet is the replacement for bit masks with none of their ambiguity.
EnumSet<Status> open = EnumSet.of(Status.OPEN); EnumMap<Status, String> labels = new EnumMap<>(Status.class);
Common misconception: That HashSet/HashMap are 'fine in general'. They are correct but wasteful for enum keys: hashing machinery for what a fixed small int can index.
Follow-up: What does EnumSet.allOf return for an enum with no constants?