Objects, Classes & OOP Design
Enums
Java enums are full classes with a fixed set of instances — they can carry fields, methods, and per-constant behavior. Use them instead of int constants, and use
EnumSet/EnumMap instead of bit fields and ordinal indexing.- Type-safe: you cannot pass an invalid value where an enum is expected (EJ 34)
- Enums can have constructors, fields, methods, and constant-specific method bodies
- Switch over enums is exhaustiveness-checked when all constants are covered
- Never rely on
ordinal()— use instance fields instead (EJ 35) EnumSetreplaces bit fields (EJ 36);EnumMapreplaces ordinal-indexed arrays (EJ 37)- Single-element enum: the most robust singleton (EJ 3)
public enum Planet {
MERCURY(3.302e+23, 2.439e6),
EARTH(5.975e+24, 6.378e6);
private final double mass, radius;
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double surfaceGravity() {
return 6.67e-11 * mass / (radius * radius);
}
}public enum Operation {
PLUS("+") { public double apply(double x, double y) { return x + y; } },
TIMES("*") { public double apply(double x, double y) { return x * y; } };
private final String symbol;
Operation(String symbol) { this.symbol = symbol; }
public abstract double apply(double x, double y);
}Every enum implicitly extends java.lang.Enum and provides values(), valueOf(String), name(), and ordinal(). Enums are serialization-safe and reflection-proof singletons per constant, which is why a one-constant enum is the sturdiest singleton implementation (EJ Item 3).