Enums and nested classes series: 1. Enums are classes · 2. Enums in production · 3. Nested classes and lambdas
Enums tend to get filed under “minor syntax” for declaring a few constants, but getting them wrong causes real production bugs. After this post you can design an enum as a class (fields, methods, strategies), avoid the traps in valueOf/values()/ordinal(), use exhaustive switches, and know when a sealed interface with records beats an enum. You should know classes, constructors, static and final first (OOP part 1, part 2); all code targets Java 21.
At a glance:
flowchart TD
Q{All values same shape?} -->|yes| E["Enum: closed set"]
Q -->|no| SI["Sealed interface + record"]
E --> C["Unique constants, compare with =="]
E --> F["Fields, methods, per-constant bodies"]
E --> V["External input: Map + Optional"]
V -.-> ST["Lookup built in static {}"]
E --> SW["Switch without default"]
The next two parts cover enums at system boundaries and nested classes. Part 2: EnumSet/EnumMap, the enum singleton, enums in databases, JSON and APIs (persist one the wrong way and inserting a constant in the middle corrupts every existing row; add a constant to an API enum and old clients break during deserialization). Part 3: the four kinds of nested class, effectively final and lambdas (an inner class registered as a listener can pin a 50 MB object in memory forever).
1. From static final constants to enums
Key idea: String/int constants let the compiler accept any string or number at all. An enum is its own type, so only the declared values compile.
public final class Roles {
public static final String ADMIN = "ADMIN";
public static final String EDITOR = "EDITOR";
public static final String VIEWER = "VIEWER";
private Roles() {}
}
void grant(String role) { ... }
grant(Roles.ADMIN); // what we meant
grant("SUPERADMIN"); // still compiles
grant("admin"); // still compiles, wrong case
Using int (static final int ADMIN = 1) is even worse: logs show a bare 1 nobody understands, and grant(STATUS_ACTIVE) (an int constant from another concept) slips through.
public enum Role { ADMIN, EDITOR, VIEWER }
void grant(Role role) { ... }
grant(Role.ADMIN); // only these three values (or null) are accepted
// grant("ADMIN"); // compile error
Beyond type safety, enums have a readable toString(), == comparison, exhaustive switches, the specialized EnumSet/EnumMap, and most importantly they let you attach data and behavior to each value.
2. An enum is a class
Key idea: the compiler turns an enum into a final class extending java.lang.Enum, with each constant a static final object created once. That’s why enums have fields, constructors and methods, and can implement interfaces.
2.1. What the compiler generates
enum Role { ADMIN, EDITOR, VIEWER } compiles into something very close to this:
public final class Role extends java.lang.Enum<Role> { // final unless a constant has a body
public static final Role ADMIN = new Role("ADMIN", 0);
public static final Role EDITOR = new Role("EDITOR", 1);
public static final Role VIEWER = new Role("VIEWER", 2);
private static final Role[] $VALUES = { ADMIN, EDITOR, VIEWER };
private Role(String name, int ordinal) { super(name, ordinal); }
public static Role[] values() { return $VALUES.clone(); }
public static Role valueOf(String name) { return Enum.valueOf(Role.class, name); }
}
The rules that follow:
- Each constant is a single object in the JVM (per class loader), so
==is correct and more null-safe thanequals. - It already implicitly
extends Enum<E>, so it can’t extend another class, but it can implement interfaces. - The constructor is always
private(declaring itpublicis a compile error). You can’tnewone, not even through reflection. EnumimplementsComparable(byordinal) andSerializable;equalsandhashCodearefinaland identity-based (they compare the object itself, not its contents).- Built-in methods:
name()(exactly as declared,final),ordinal()(position, from 0),toString()(defaults toname(), overridable),compareTo,getDeclaringClass().
Enum<E extends Enum<E>> is a recursive generic bound (a type that refers to itself); see the generics post.
2.2. Fields, constructors and methods
Fields should be final: an enum constant is a JVM-wide shared singleton, so a mutable field is global mutable state (state anyone anywhere can change).
public enum Priority {
LOW("Low", Duration.ofDays(3)),
MEDIUM("Medium", Duration.ofHours(24)),
HIGH("High", Duration.ofHours(4)),
CRITICAL("Critical", Duration.ofMinutes(30));
private final String label;
private final Duration sla;
Priority(String label, Duration sla) { // implicitly private
this.label = label;
this.sla = sla;
}
public String label() { return label; }
public Duration sla() { return sla; }
public boolean needsPaging() {
return this.compareTo(HIGH) >= 0; // HIGH and CRITICAL
}
}
The list of constants must come first in the enum body, terminated by ; if fields or methods follow.
2.3. Constant-specific bodies
Each constant can have its own body that overrides the enum’s methods. The enum usually declares an abstract method to force every constant to implement it:
public enum ShippingMethod {
STANDARD {
@Override
public BigDecimal fee(BigDecimal weightKg) {
return new BigDecimal("15000").add(weightKg.multiply(new BigDecimal("3000")));
}
},
EXPRESS {
@Override
public BigDecimal fee(BigDecimal weightKg) {
return STANDARD.fee(weightKg).multiply(BigDecimal.TWO);
}
@Override
public boolean trackable() { return true; }
},
PICKUP {
@Override
public BigDecimal fee(BigDecimal weightKg) { return BigDecimal.ZERO; }
};
public abstract BigDecimal fee(BigDecimal weightKg);
public boolean trackable() { return false; }
}
Compared with one method containing switch (this), each constant’s logic sits right next to the constant, and adding a constant without implementing fee is a compile error.
A constant with a body is an anonymous subclass: getClass and getDeclaringClass
A constant with a body is actually an anonymous subclass (a nameless subclass) of the enum. ShippingMethod.EXPRESS.getClass() returns ShippingMethod$2, not ShippingMethod, and getClass().isEnum() is false. Code that needs the enum type (for example a hand-written serializer) must use getDeclaringClass(). It’s also why the generated class is no longer final once a constant has a body.
2.4. Implementing interfaces: strategies as enums
Enums can implement interfaces, so each constant is a ready-made strategy (an interchangeable way of doing something) with no object creation needed:
public enum Operation implements DoubleBinaryOperator {
PLUS("+", (a, b) -> a + b),
MINUS("-", (a, b) -> a - b),
TIMES("*", (a, b) -> a * b),
DIVIDE("/", (a, b) -> a / b);
private final String symbol;
private final DoubleBinaryOperator impl;
Operation(String symbol, DoubleBinaryOperator impl) {
this.symbol = symbol;
this.impl = impl;
}
@Override
public double applyAsDouble(double a, double b) { return impl.applyAsDouble(a, b); }
private static final Map<String, Operation> BY_SYMBOL = new HashMap<>();
static {
for (Operation op : values()) BY_SYMBOL.put(op.symbol, op);
}
public static Optional<Operation> fromSymbol(String symbol) {
return Optional.ofNullable(BY_SYMBOL.get(symbol));
}
}
// Instead of a chain of if (op.equals("+")) ... else if ...
double result = Operation.fromSymbol("*").orElseThrow().applyAsDouble(3, 4); // 12.0
- A lambda passed to the constructor is shorter when constants differ by a single expression; a body per constant (section 2.3) fits better when each overrides several methods or has longer logic.
- Callers only depend on
DoubleBinaryOperator, so you can later add another enum (ScientificOperation) implementing it. That’s how you “extend” an otherwise closed set.
3. values(), valueOf() and ordinal()
Key idea: valueOf matches the name exactly and throws when it’s wrong, so never feed external input straight into it. ordinal() changes when someone reorders the constants, so don’t build business logic on it.
valueOf(String) is case-sensitive, doesn’t trim, and throws instead of returning null:
Color.valueOf("RED"); // RED
Color.valueOf("red"); // IllegalArgumentException: No enum constant Color.red
Color.valueOf(null); // NullPointerException: Name is null
For input from users, query parameters or CSV files, don’t let that exception surface as a 500. Look up safely, normalize the input, return an Optional:
private static final Map<String, OrderStatus> BY_NAME = new HashMap<>();
static {
for (OrderStatus s : values()) BY_NAME.put(s.name(), s);
}
public static Optional<OrderStatus> parse(String raw) {
if (raw == null) return Optional.empty();
return Optional.ofNullable(BY_NAME.get(raw.strip().toUpperCase(Locale.ROOT)));
}
ordinal() is the declaration position, there for EnumSet/EnumMap inside the JDK. Reordering, inserting a constant in the middle or removing one all shift the other ordinals. If you need a stable number (a code sent to another system, a priority level), declare a dedicated field.
values() allocates a new array, and compareTo is ordinal-based
compareTo is ordinal-based too. Using it for “levels” like needsPaging() in section 2.2 is fine when declaration order is the business order. Say so in a comment so nobody later sorts the constants alphabetically.
4. Switching on enums and exhaustiveness
Key idea: a switch expression on an enum without a default is checked for exhaustiveness (covering every case): a missing constant doesn’t compile. Adding a constant becomes a to-do list produced by the compiler.
Switch expressions arrived in Java 14 (see Java basics):
static String label(Status s) {
return switch (s) {
case ACTIVE -> "Active";
case BLOCKED -> "Blocked";
}; // add Status.DELETED -> compile error right here, which is what we want
}
The check only holds when every call site is recompiled. If the enum lives in a library that gets upgraded while the caller isn’t rebuilt, a switch expression that meets an unknown constant throws MatchException (Java 21; previously IncompatibleClassChangeError). An old-style switch statement silently matches nothing.
null in a switch and how to write case labels
- Switching on an enum variable that is
nullthrowsNullPointerException, even with adefault. Since Java 21 you can writecase null ->whennullis a legitimate case. caselabels use the bare constant name (case ACTIVE), noStatus.prefix needed (since Java 21 the qualified form is allowed too).
When each case carries different data: sealed interfaces and records
Enums fit when every value has the same shape (the same fields). When each case carries different data (a card needs the last four digits, a bank transfer an IBAN, a wallet a provider and a balance), an enum with a pile of nullable fields is a bad design. The right tool is a sealed interface (Java 17+, an interface only the listed classes may implement) plus records, with pattern matching in switch (Java 21), which is also checked for exhaustiveness.
sealed interface Payment permits Card, BankTransfer, Wallet {}
record Card(String last4) implements Payment {}
record BankTransfer(String iban) implements Payment {}
record Wallet(String provider, BigDecimal balance) implements Payment {}
static String describe(Payment p) {
return switch (p) {
case Card c -> "card *" + c.last4();
case BankTransfer(String iban) -> "bank " + iban; // record pattern
case Wallet w when w.balance().signum() == 0 -> "empty wallet";
case Wallet w -> "wallet " + w.provider();
}; // no default: the compiler knows there are exactly three types
}
Exercises
1. Parsing an order status safely
Task (paraphrased): create an order-status enum with pending, shipped, delivered and cancelled; each status has a Vietnamese description and a method telling whether it’s final (delivered or cancelled). Read a string typed by the user and print the description and the final flag; on invalid input, report it instead of crashing.
Solution to Exercise 1: a lookup map and normalized input
Don’t call valueOf directly (it throws and is case-sensitive); build a lookup map once and normalize the input.
import java.util.*;
public class OrderStatusDemo {
enum OrderStatus {
PENDING("Chờ xác nhận"),
SHIPPED("Đang giao hàng"),
DELIVERED("Đã giao"),
CANCELLED("Đã huỷ");
private final String label;
OrderStatus(String label) { this.label = label; }
public String label() { return label; }
public boolean isFinal() {
return this == DELIVERED || this == CANCELLED;
}
private static final Map<String, OrderStatus> BY_NAME = new HashMap<>();
static {
for (OrderStatus s : values()) BY_NAME.put(s.name(), s);
}
public static Optional<OrderStatus> parse(String raw) {
if (raw == null) return Optional.empty();
return Optional.ofNullable(BY_NAME.get(raw.strip().toUpperCase(Locale.ROOT)));
}
}
public static void main(String[] args) {
for (String input : List.of("delivered", " SHIPPED ", "SHIPPING")) {
OrderStatus.parse(input).ifPresentOrElse(
s -> System.out.printf("%s -> %s, final=%b%n", input, s.label(), s.isFinal()),
() -> System.out.printf("%s -> invalid status%n", input));
}
}
}
// delivered -> Đã giao, final=true
// SHIPPED -> Đang giao hàng, final=false
// SHIPPING -> invalid status
The map is built in a static block placed after the constants, so it avoids the “constructor uses a static field” error.
2. Upgrading it to a state machine
Task: extend exercise 1 into a real state machine: add paid and refunded statuses, declare which status may move to which, and reject invalid moves (e.g. a delivered order can’t be cancelled).
Solution to Exercise 2: a transition table in an EnumMap
The transition table is an EnumMap<OrderStatus, Set<OrderStatus>> built in a static block (you can’t pass EnumSet.of(SHIPPED) to PENDING’s constructor; that’s a forward reference). The static block also checks that every status is covered, so adding a constant and forgetting its transitions fails at startup rather than in the middle of a request.
enum OrderStatus {
PENDING, PAID, SHIPPED, DELIVERED, CANCELLED, REFUNDED;
private static final Map<OrderStatus, Set<OrderStatus>> NEXT = new EnumMap<>(OrderStatus.class);
static {
NEXT.put(PENDING, EnumSet.of(PAID, CANCELLED));
NEXT.put(PAID, EnumSet.of(SHIPPED, REFUNDED));
NEXT.put(SHIPPED, EnumSet.of(DELIVERED));
NEXT.put(DELIVERED, EnumSet.of(REFUNDED));
NEXT.put(CANCELLED, EnumSet.noneOf(OrderStatus.class));
NEXT.put(REFUNDED, EnumSet.noneOf(OrderStatus.class));
for (OrderStatus s : values()) {
if (!NEXT.containsKey(s)) throw new IllegalStateException("No transitions for " + s);
}
}
public boolean canMoveTo(OrderStatus target) { return NEXT.get(this).contains(target); }
public boolean isTerminal() { return NEXT.get(this).isEmpty(); }
}
final class Order {
private final String id;
private OrderStatus status = OrderStatus.PENDING;
Order(String id) { this.id = id; }
void moveTo(OrderStatus target) {
if (!status.canMoveTo(target)) {
throw new IllegalStateException(
"Order %s: %s -> %s is not allowed".formatted(id, status, target));
}
status = target;
}
}
Order o = new Order("A001");
o.moveTo(OrderStatus.PAID);
o.moveTo(OrderStatus.SHIPPED);
o.moveTo(OrderStatus.CANCELLED); // IllegalStateException: Order A001: SHIPPED -> CANCELLED is not allowed
Alternative: a Set<OrderStatus> next() method with a switch expression on this. Upside: the compiler catches a missing constant at build time; downside: a new EnumSet per call unless you cache it. In a real system, transitions with extra conditions (refunds only within 7 days) belong in a service; the enum only holds the table of valid moves.
Remember
- Explain why an enum is safer than
String/intconstants, and when a set of values belongs in a database table. - Describe what the compiler generates for an enum, and why
==is the right comparison. - Know why an enum constructor can’t use static fields, and where to build lookup tables instead.
- Parse an enum from user input without a 500 and without depending on the locale.
- Know when to leave out
defaultin a switch, and when to move to a sealed interface + records.
Interview questions
Junior
Why use an enum instead of static final String constants?
Because an enum is a distinct type: the compiler only accepts the declared values, while with String any string compiles.
With String, mistakes only show up at runtime. Enums can also be compared with ==, used in switches with exhaustiveness checks, carry fields and methods per value, and come with the fast EnumSet/EnumMap.
Can an enum have a constructor? Why can’t you call new on it?
Yes, but the constructor is always implicitly private: the only instances are the constants the JVM creates once when the enum is loaded.
Enums have fields, constructors and methods like classes. You can’t new one and can’t create one via reflection (Cannot reflectively create enum objects). An enum can’t extend another class because it already implicitly extends Enum, though it can implement interfaces.
Do you compare enum values with == or equals?
==: each constant is a single instance, so == is semantically correct, fast and null-safe.
status == Status.ACTIVE doesn’t throw when status is null. == is also type-checked at compile time: comparing two different enum types with == is a compile error, whereas equals silently returns false.
Mid
What does Status.valueOf("active") return when the constant is named ACTIVE? How do you parse enums from user input?
It throws IllegalArgumentException, because valueOf matches name() exactly and is case-sensitive; null throws NullPointerException.
For external input, prebuild a Map<String, Status> (or one keyed by a dedicated code), normalize with strip() and toUpperCase(Locale.ROOT), and return an Optional. In the web layer, map invalid values to a 400 rather than letting them become a 500.
A switch expression on an enum has no default. What happens when you add a new constant?
If the calling code is recompiled: a compile error, which is good. If it isn’t rebuilt: a MatchException at runtime.
- Recompiled: “the switch expression does not cover all possible input values”; the compiler points to every place that needs handling.
- The enum lives in a library that gets upgraded without rebuilding the caller: hitting the new constant makes the switch expression throw
MatchException(Java 21; previouslyIncompatibleClassChangeError). - Adding a
defaultturns the check off, so only do it for enums owned by someone else, and make thedefaultbranch fail loudly.
Senior
When do you choose a sealed interface with records over an enum?
When the cases carry different data; for a plain fixed list of same-shaped values, stick with an enum.
For example a card payment needs the last four digits, a bank transfer an account number, a wallet a provider. An enum forces every constant to have the same fields and be a singleton, which ends in a pile of nullable fields. A sealed interface with records gives each case its own type and data, allows many instances, and pattern-matching switches are still checked for exhaustiveness. You give up values() and EnumSet/EnumMap, and persistence or JSON needs a discriminator.
Useful phrases for interviews
- “I’d model this as an enum because the set of values is closed and owned by our code; if admins can add values, it belongs in a table.”
- “I deliberately leave out the
defaultso the compiler flags every switch when someone adds a constant.” - “Each case carries different data, so a sealed interface with records fits better than an enum with nullable fields.”
- “An enum constant is a singleton per JVM, so comparing with
==is correct and null-safe.” - “I parse external input through a prebuilt lookup map that returns an
Optional, instead of lettingvalueOfthrow.” - “With constant-specific bodies, forgetting to implement the abstract method for a new constant is a compile error.”
- “The transition table lives in the enum, so an illegal state change fails fast with a clear message.”
- “I never rely on
ordinal()in business code; if I need a stable number, I add an explicit field.”
Notes based on the Hỏi Dân IT Java Core material plus my own research, rewritten in my own words.