In Java, enums are not just lists of string constants; they are full classes. You can add constructors, instance variables, and methods to them. One of the most powerful features of Java enums is the ability to write **constant-specific class bodies**, allowing specific enum items to override class methods or implement abstract methods uniquely.
Imagine a smart light switch panel with three buttons: **ON**, **OFF**, and **PARTY**.
Each button is a switch option, but they trigger different behaviors when pressed:
- Pressing ON executes standard behavior: turns lights to 100%.
- Pressing OFF executes standard behavior: turns lights to 0%.
- Pressing PARTY does something completely custom: it overrides the standard switch behavior to cycle colors dynamically and start playing dance music!
In Java, each switch button is an enum constant, and the PARTY button has a **custom class body** that overrides the standard click behavior.
Java Implementation
In this example, enum constants define character representations. The constant C defines a custom body that overrides the method printSmallCase() to execute unique printing logic:
package io.practise.ocpPractise;
public enum characters {
A("a"),
B("b"),
// Constant C provides a constant-specific class body that overrides printSmallCase
C("c") {
@Override
public void printSmallCase() {
System.out.print(this.getCase());
}
};
private String smallCase;
// Private constructor for enum constants
private characters(String se) {
this.smallCase = se;
}
public String getCase() {
return this.smallCase;
}
// Base package-private method
void printSmallCase() {
throw new UnsupportedOperationException("Not supported yet.");
}
}
Conclusion
Constant-specific method bodies enable you to implement the Strategy Design Pattern directly within a clean Enum structure, eliminating messy switch-case logic blocks across your codebase.