Practical Enum Techniques
Enum with Custom Methods
Adding Behavior to Enum Constants
public enum Operation {
ADD("+") {
public double apply(double x, double y) { return x + y; }
},
SUBTRACT("-") {
public double apply(double x, double y) { return x - y; }
},
MULTIPLY("*") {
public double apply(double x, double y) { return x * y; }
},
DIVIDE("/") {
public double apply(double x, double y) {
if (y == 0) throw new ArithmeticException("Division by zero");
return x / y;
}
};
private final String symbol;
Operation(String symbol) {
this.symbol = symbol;
}
public abstract double apply(double x, double y);
public String getSymbol() {
return symbol;
}
}
Enum as a State Machine
public enum TrafficLight {
RED {
@Override
public TrafficLight next() {
return GREEN;
}
},
GREEN {
@Override
public TrafficLight next() {
return YELLOW;
}
},
YELLOW {
@Override
public TrafficLight next() {
return RED;
}
};
public abstract TrafficLight next();
}
Enum Singleton Pattern
public enum DatabaseConnection {
INSTANCE;
private Connection connection;
private DatabaseConnection() {
// Initialize database connection
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb");
} catch (SQLException e) {
throw new RuntimeException("Database connection failed", e);
}
}
public Connection getConnection() {
return connection;
}
}
Enum Techniques Comparison
Technique |
Use Case |
Advantages |
Limitations |
Custom Methods |
Complex logic |
Flexible |
Can increase complexity |
State Machine |
Finite states |
Clear transitions |
Limited to predefined states |
Singleton |
Single instance |
Thread-safe |
Less flexible than class-based singleton |
Enum with Generics
public enum Converter<T> {
STRING_TO_INTEGER {
public Integer convert(String value) {
return Integer.parseInt(value);
}
},
STRING_TO_DOUBLE {
public Double convert(String value) {
return Double.parseDouble(value);
}
};
public abstract T convert(String value);
}
Enum Workflow
graph TD
A[Enum Definition] --> B{Technique Type}
B -->|Custom Methods| C[Add Specific Behavior]
B -->|State Machine| D[Define State Transitions]
B -->|Singleton| E[Ensure Single Instance]
C --> F[Implement Logic]
D --> F
E --> F
Advanced Enum Techniques
Using EnumSet
import java.util.EnumSet;
public class EnumSetDemo {
enum Permissions {
READ, WRITE, EXECUTE, DELETE
}
public static void main(String[] args) {
EnumSet<Permissions> userPermissions = EnumSet.of(
Permissions.READ,
Permissions.WRITE
);
}
}
Enum in Switch Statements
public class EnumSwitch {
public static void handleDay(DaysOfWeek day) {
switch (day) {
case SATURDAY:
case SUNDAY:
System.out.println("Weekend");
break;
default:
System.out.println("Weekday");
}
}
}
Best Practices
- Use enums for type-safe constant collections
- Implement meaningful methods within enums
- Leverage enum's built-in features
- Consider performance and readability
With LabEx's comprehensive guide, you can master advanced enum techniques in Java, elevating your programming skills to the next level.