Enums
Prerequisites: Encapsulation in practice
An enum is a fixed, named set of constant values — safer than using
plain Strings or numbers to represent a closed set of options,
since the compiler rejects anything not in the list.
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
Day today = Day.WEDNESDAY;
String label = switch (today) {
case SATURDAY, SUNDAY -> "Weekend";
default -> "Weekday";
};
System.out.println(label); // Weekday
An enum can also carry fields and methods, making it more powerful than a plain named constant:
enum Planet {
MERCURY(3.3e23), EARTH(5.9e24);
final double mass;
Planet(double mass) {
this.mass = mass;
}
}
Common mistakes
- Using a
String("MONDAY") to represent a fixed set of options instead of anenum— a typo like"MONDDAY"compiles fine and fails silently at runtime; an invalid enum constant simply won't compile.