Constant-Specific Method Implementations
What you'll learn: How to give each enum constant its own unique behavior by overriding methods on a per-constant basis.
The Core Idea
You already know that enums can declare abstract methods that all constants must implement. But what if you want each constant to behave differently without declaring the method abstract? Java lets you override methods directly on individual enum constants using anonymous class syntax. This means each constant can have its own specialized implementation of a method, even if the enum provides a default version.
How It Works
When you declare an enum constant, you can add curly braces {} right after it, just like creating an anonymous class. Inside those braces, you can override any method defined in the enum class.
public enum Operation {
PLUS {
@Override
public int apply(int x, int y) {
return x + y;
}
},
MINUS {
@Override
public int apply(int x, int y) {
return x - y;
}
};
public abstract int apply(int x, int y);
}
Each constant (PLUS, MINUS) overrides the apply method with its own logic. You can also override non-abstract methods if needed.
Why This Matters
This pattern eliminates the need for switch statements to handle constant-specific behavior. Each constant encapsulates its own logic, making your code cleaner and safer—adding a new constant forces you to provide its implementation immediately.
Key Takeaway: Use constant-specific method implementations to give each enum constant unique behavior by overriding methods using anonymous class syntax within the constant declaration itself.