5 · Intermediate · lesson 26 of 41
Enums
A fixed, type-safe set of named constants — that can also have behavior.
Java
enum Direction {
NORTH( 0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);
final int dx, dy;
Direction(int dx, int dy) { this.dx = dx; this.dy = dy; }
Direction opposite() {
return values()[(ordinal() + 2) % 4];
}
}Key takeaways
- ✓Enums can carry fields and methods.
- ✓Prefer enums over public static final int for named sets.