Java Enums — Methods, Fields, and Interfaces
Advanced enum patterns: enums with fields, abstract methods, implementing interfaces, and enum maps.
import java.util.*;
import java.util.function.DoubleBinaryOperator;
// Enum with fields and methods
public enum HttpStatus {
OK(200, "OK"),
CREATED(201, "Created"),
BAD_REQUEST(400, "Bad Request"),
NOT_FOUND(404, "Not Found"),
INTERNAL_ERROR(500, "Internal Server Error");
private final int code;
private final String reason;
HttpStatus(int code, String reason) {
this.code = code;
this.reason = reason;
}
public int code() { return code; }
public String reason() { return reason; }
public boolean isError() { return code >= 400; }
// Reverse lookup
private static final Map<Integer, HttpStatus> BY_CODE = new HashMap<>();
static { for (var s : values()) BY_CODE.put(s.code, s); }
public static HttpStatus fromCode(int code) {
return Optional.ofNullable(BY_CODE.get(code))
.orElseThrow(() -> new IllegalArgumentException("Unknown: " + code));
}
}
// Enum implementing interface (strategy pattern)
enum MathOp implements DoubleBinaryOperator {
ADD {
public double applyAsDouble(double a, double b) { return a + b; }
},
SUBTRACT {
public double applyAsDouble(double a, double b) { return a - b; }
},
MULTIPLY {
public double applyAsDouble(double a, double b) { return a * b; }
};
public double calculate(double a, double b) {
return applyAsDouble(a, b);
}
}
// Usage
class EnumDemo {
public static void main(String[] args) {
HttpStatus status = HttpStatus.fromCode(404);
System.out.printf("%d %s (error: %b)%n", status.code(), status.reason(), status.isError());
double result = MathOp.ADD.calculate(10, 5);
System.out.println(result); // 15.0
// EnumSet — efficient set of enum values
EnumSet<HttpStatus> errors = EnumSet.of(HttpStatus.BAD_REQUEST, HttpStatus.NOT_FOUND);
EnumMap<HttpStatus, String> messages = new EnumMap<>(HttpStatus.class);
messages.put(HttpStatus.OK, "Success!");
}
}Use Cases
- Type-safe constants with behavior
- Strategy pattern using enum methods
- Efficient enum-based lookup tables
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Java Optional — Avoid NullPointerException
Use Optional to handle nullable values safely with map, flatMap, orElse, and ifPresent patterns.
Best for: Eliminating NullPointerException in business logic
Builder Pattern — Fluent Object Construction
Implement the Builder pattern for complex objects with validation, immutability, and method chaining.
Best for: Constructing complex objects with many optional parameters
Singleton Pattern — Thread-Safe Approaches
Implement thread-safe singletons in Java: enum, holder class, double-checked locking, and eager init.
Best for: Application-wide configuration managers
Strategy Pattern with Lambdas
Implement the Strategy pattern using interfaces and Java lambdas for flexible algorithm selection.
Best for: Swappable pricing or discount algorithms