library
intermediateEnums & Enum Methods
Use enums as type-safe constants with behavior — fields, methods, abstract methods, and implementing interfaces.
Java enums are much more powerful than C-style constants. An enum is a special class that extends java.lang.Enum with a fixed set of instances. Each constant is a singleton object.
Enum = a deck of specific cards. You can't create new cards at runtime, and each card can have its own behavior (ace counts as 1 or 11).
Key Concepts
1
Beyond simple constants, enums can have:
1. Fields and constructors (constants pass arguments to the constructor)
2. Methods (shared behavior across all constants)
3. Abstract methods (each constant provides its own implementation — constant-specific behavior)
4. Interface implementations
5. Their own static methods and fields
2
Key features:
- Thread-safe singleton: each enum constant is initialized once, lazily, when the class is loaded. This makes enum the best way to implement Singleton in Java.
- values() returns all constants in declaration order.
- valueOf(String) returns the constant matching the name (case-sensitive, throws IllegalArgumentException if not found).
- ordinal() returns the position (0-based). Avoid relying on ordinal — it changes when constants are reordered.
- Enums can be used in switch statements and (since Java 14) switch expressions.
- EnumSet and EnumMap are highly optimized collections for enum keys.
3
Enums cannot be extended (final by design) and cannot be instantiated with new.