Unravel › Java concepts › OOP and types
Enums with fields and behaviour
A Java enum is a full class with a fixed set of instances.
Learn these first
At a glance
A list of reserved seat types where each type comes with its own price tag and rules printed on it, instead of a separate rulebook you must look up.
- 1enum Planet { EARTH(5.97e24, 6.37e6); private final double mass, radius; Planet(double m, double r) { ..} double gravity() { ... } } declares constants with arguments, fields and methods. The constructor is always private.
- 2Per-constant behaviour: declare abstract double apply(double a, double b); in the enum and give each constant a body: PLUS { double apply(...) { return a + b; } }
- 3Enums can implement interfaces, so a PaymentType can be passed as a Strategyvalues(), valueOf(String), ordinal() and name() come for free; EnumMap and EnumSet give compact maps and sets keyed by enum.
- 4Look up by a code: keep a static Map<String, Status> built in a static block, or write static Status of(String code) with a loop; valueOf only works with the exact constant name and throws IllegalArgumentException
- Do not store ordinal() in a database or file: reordering the constants changes the meaning
- Enums are singletons per constant and safe to compare with ==
- The compiler turns each enum into a final class extending java.lang.Enum with a static field per constant, initialised in <clinit>
public enum Operation { PLUS("+", 1) { double apply(double a, double b) { return a + b; } }, TIMES("*", 2) { double apply(double a, double b) { return a * b; } }; private final String symbol; private final int priority; Operation(String symbol, int priority) { this.symbol = symbol; this.priority = priority; } abstract double apply(double a, double b); static Operation of(String symbol) { for (Operation o : values()) if (o.symbol.equals(symbol)) return o; throw new IllegalArgumentException("unknown " + symbol); }}Read the full explanation (about 2 min)
A Java enum is a full class with a fixed set of instances. Each constant can carry fields, take constructor arguments and even override methods, which replaces long switch statements on a status or type.
A mental model
A list of reserved seat types where each type comes with its own price tag and rules printed on it, instead of a separate rulebook you must look up.
How it works
enum Planet { EARTH(5.97e24, 6.37e6); private final double mass, radius; Planet(double m, double r) { ... } double gravity() { ... } } declares constants with arguments, fields and methods. The constructor is always private.
Per-constant behaviour: declare abstract double apply(double a, double b); in the enum and give each constant a body: PLUS { double apply(...) { return a + b; } }.
Enums can implement interfaces, so a PaymentType can be passed as a Strategy. values(), valueOf(String), ordinal() and name() come for free; EnumMap and EnumSet give compact maps and sets keyed by enum.
Look up by a code: keep a static Map<String, Status> built in a static block, or write static Status of(String code) with a loop; valueOf only works with the exact constant name and throws IllegalArgumentException.
Going deeper
Do not store ordinal() in a database or file: reordering the constants changes the meaning. Store the name (@Enumerated(EnumType.STRING) in JPA) or an explicit code field.
Enums are singletons per constant and safe to compare with ==. They are also the safest singleton implementation, and serialization keeps them unique.
Switch over an enum without default and the compiler (with a switch expression) tells you when a new constant is not handled, which is why adding a default that throws is a common safety net for older switch statements.
Under the hood
The compiler turns each enum into a final class extending java.lang.Enum with a static field per constant, initialised in <clinit>. A constant with a body is an anonymous subclass of the enum.
Common mistakes
- Persisting
ordinal(). - Using
valueOfon untrusted text without handling the exception. - Putting mutable state in enum constants (it is global).
How Unravel recognises it
When you paste code, Unravel looks for these signs of enums with fields and behaviour. Spotting them yourself is a good habit when you read unfamiliar code:
- Language constructs:
enum-fieldsenumconstructor
Part of a learning path
- Object-oriented Java in depth · previous: Copying objects: clone and copy constructors · next: Custom annotations
Related concepts
Frequently asked questions
What is Enums with fields and behaviour?
A Java enum is a full class with a fixed set of instances. Each constant can carry fields, take constructor arguments and even override methods, which replaces long switch statements on a status or type.
What are the most common mistakes with Enums with fields and behaviour?
Persisting ordinal(). Using valueOf on untrusted text without handling the exception. Putting mutable state in enum constants (it is global).
How can I see Enums with fields and behaviour in real code?
Paste your own Java into Unravel and it will point out where enums with fields and behaviour appears, explain how it works at the detail level you choose, and draw the flow of the code around it.