Enums: Type-Safe Constants
Introduction
An enum defines a fixed set of named constants—days of week, order status, difficulty level. Enums are classes in Java: they can have fields, constructors, and methods, and they work well with switch.
Prerequisites
- Classes
- Conditionals (
switch)
Why Not Use Strings or int Codes?
String status = "SHIPPED"; // typo "SHIPED" only fails at runtime
int statusCode = 2; // magic numbers — unclear meaningEnums give compile-time checks and IDE autocomplete:
OrderStatus status = OrderStatus.SHIPPED;1) Basic Enum
public enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}Day today = Day.MONDAY;
System.out.println(today); // MONDAY
System.out.println(today.name()); // "MONDAY"
System.out.println(today.ordinal()); // 0 (position — avoid relying on it)2) Enum with Fields and Constructor
Enums can carry data. Constructors are private (only enum constants call them):
Difficulty d = Difficulty.HARD;
System.out.println(d.getLabel()); // Expert3) Enum Methods
Add behavior per constant:
Constant-specific bodies are advanced but common in frameworks.
4) switch with Enums
Modern switch is clean and type-safe:
Day day = Day.SATURDAY;
String type = switch (day) {
case SATURDAY, SUNDAY -> "Weekend";
default -> "Weekday";
};
System.out.println(type);Classic style still works:
switch (day) {
case SATURDAY:
case SUNDAY:
System.out.println("Weekend");
break;
default:
System.out.println("Weekday");
break;
}5) values() and valueOf
for (Day d : Day.values()) {
System.out.println(d);
}
Day parsed = Day.valueOf("FRIDAY");valueOf throws if the name is invalid—validate user input before calling.
6) Enums Implementing Interfaces
Enums can implement interfaces like any class (Interfaces):
Real Mini Example: Order Status
Common Beginner Mistakes
Comparing with == vs equals
Both work for enum constants (singleton instances). Prefer == for enums; use equals when accepting unknown types from strings after valueOf.
Relying on ordinal() for Business Logic
Order of declaration can change. Store explicit int level fields instead.
Public Enum Constructor
Enum constructors must be private (or package-private). Constants are created by the compiler.
Mini Practice
Create Planet enum with name and gravity field; loop values() and print each.
What’s Next
Reuse behavior with Inheritance and Abstract Classes.
FAQ
Is enum a class?
Yes. Each constant is a public static final instance of the enum type.
Can enums extend other classes?
No multiple inheritance—enums implicitly extend java.lang.Enum. They can implement interfaces.
When should I use enum vs static final constants?
Use enum when you have a fixed set with behavior or safe switching. Simple int constants are rare in modern Java style.
Can I use enum in generics?
Yes: Map<OrderStatus, String>.
How do enums relate to record?
Both model domain concepts; enums are for fixed variants, records for data snapshots.