Enums as Objects
Enum constants are objects, so each one can carry data and its own method body.
Open this lesson in the learning hubKey points
- An enum is a class whose instances are fixed and named. Each constant is one object, created once.
- Constants can take constructor arguments, so an enum carries data as well as a name.
- A constant can also override a method in its own body, which is polymorphism with no subclass to write.
- That kills the switch:
op.apply(a, b)instead of a switch that someone will forget to update. - Enums are comparable, serializable and safe with
==. UseEnumMapandEnumSetover HashMap. - Do not lean on
ordinal(). Reordering constants would silently change its meaning; store a field instead.
Example
import java.util.EnumMap;
import java.util.Map;
public class Main {
enum Op {
PLUS("+") { @Override int apply(int a, int b) { return a + b; } },
MINUS("-") { @Override int apply(int a, int b) { return a - b; } },
TIMES("*") { @Override int apply(int a, int b) { return a * b; } };
private final String symbol;
Op(String symbol) { this.symbol = symbol; } // constructors are always private
abstract int apply(int a, int b); // each constant supplies a body
String symbol() { return symbol; }
}
public static void main(String[] args) {
for (Op op : Op.values()) {
System.out.println("6 " + op.symbol() + " 3 = " + op.apply(6, 3));
}
Op picked = Op.valueOf("TIMES");
System.out.println("picked " + picked + " at ordinal " + picked.ordinal());
System.out.println("one instance per constant? " + (picked == Op.TIMES));
Map<Op, Integer> uses = new EnumMap<>(Op.class); // array-backed, very fast
uses.put(Op.PLUS, 3);
uses.put(Op.TIMES, 1);
System.out.println("usage " + uses);
}
}
Give the enum the behaviour and the switch statements disappear.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the OOP course, and every lesson in it is listed on the OOP contents page.