Appearance
Lesson 04 · Enums
Objectives
After this lesson you will be able to:
- Declare enums with fields, constructors, and methods.
- Use
values(),valueOf(),ordinal(), andname(). - Use enums in
switchand give constants per-constant behavior.
Basics
An enum is a fixed set of named constant instances. Each constant is a singleton object of the enum type.
java
enum Day { MON, TUE, WED }
Day d = Day.MON;
d.name(); // "MON"
d.ordinal(); // 0 (declaration position, zero-based)
Day.valueOf("TUE"); // Day.TUE — throws IllegalArgumentException if no match
Day.values(); // Day[] {MON, TUE, WED} — a fresh array each callExam trap
valueOf is case-sensitive and throws IllegalArgumentException (not NumberFormatException) for an unknown name. Avoid relying on ordinal() for logic or persistence — reordering constants silently changes the numbers.
Fields, constructors, methods
An enum can have state and behavior. The constructor is implicitly private and runs once per constant, when the constant is created.
java
enum Planet {
EARTH(5.97e24, 6.37e6),
MARS(6.42e23, 3.39e6); // constants first, with constructor args
private final double mass, radius;
Planet(double mass, double radius) { // implicitly private
this.mass = mass; this.radius = radius;
}
double gravity() { return 6.67e-11 * mass / (radius * radius); }
}
Planet.EARTH.gravity();Gotcha
The constant list must come first in the body, ended with a semicolon before any fields/methods. An enum cannot be extended and cannot extend another class (it already extends java.lang.Enum), though it can implement interfaces.
Per-constant bodies and switch
Each constant may override a method with a constant-specific class body:
java
enum Op {
PLUS { public int apply(int a, int b) { return a + b; } },
TIMES { public int apply(int a, int b) { return a * b; } };
public abstract int apply(int a, int b);
}
Op.PLUS.apply(2, 3); // 5Enums shine in switch, where you reference constants by simple name:
java
String label = switch (d) {
case MON, TUE, WED -> "weekday"; // not Day.MON — just MON
};Key Takeaways
- Each enum constant is a singleton instance;
name()is its identifier,ordinal()its 0-based position (don't depend on it). values()returns a fresh array;valueOfis case-sensitive and throwsIllegalArgumentExceptionon a miss.- Enums can have fields, methods, and a (private) constructor; constants are listed first.
- Enums can implement interfaces and give per-constant behavior, but cannot be extended.
- In
switch, refer to constants by their simple name (MON, notDay.MON).
Lesson Quiz
What does Day.valueOf("mon") do, given enum Day { MON, TUE }?
What is Day.WED.ordinal() given enum Day { MON, TUE, WED }?
An enum constructor is implicitly...
Which is TRUE about enums?
In a switch on a Day value, how do you reference the constant MON?
Next: Records. Run the matching code in labs/src/main/java/com/jse21/m03_oop/.