Lesson 32: Understanding and Using Enumerations (Enums)
An enumeration (Enum) is a special class type used to define a fixed set of constants. They are far safer and more expressive than using standard integer constants.
1. Basic Enum Declaration
Enums ensure type safety, meaning a variable declared as an Enum type can only take one of the defined constant values.
java public enum DayOfWeek { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
// Usage: DayOfWeek today = DayOfWeek.MONDAY;
// Safe comparison: if (today == DayOfWeek.FRIDAY) { System.out.println("It's Friday!"); }
// Enums work perfectly with switch statements (modern or traditional): switch (today) { case SATURDAY, SUNDAY -> System.out.println("Weekend!"); default -> System.out.println("Work day."); }
2. Enums as Enhanced Classes
In Java, enums are full-fledged classes. They can have constructors, instance fields, and methods, allowing you to associate behavior or data with each constant.
java public enum CoffeeSize { SMALL(8), MEDIUM(12), LARGE(16);
private final int ounces;
// Constructor must be private or package-private
CoffeeSize(int ounces) {
this.ounces = ounces;
}
// Getter method
public int getOunces() {
return ounces;
}
}
// Usage: CoffeeSize myCoffee = CoffeeSize.MEDIUM; System.out.println("Size: " + myCoffee.getOunces() + " oz.");
Standard Enum Methods: All enums inherit methods like name() (returns the constant name as a string) and ordinal() (returns the index of the constant, starting at 0).