Multiple Fields and Complex Enum State
What you'll learn: How to build enums with multiple fields and constructors to represent rich, structured domain data.
The Core Idea
You've already learned that enums can have fields, constructors, and methods. Now we take it further: enums can hold multiple fields of different types, creating mini data structures that combine several related pieces of information. This transforms enums from simple constant lists into powerful domain models.
Think of each enum constant as a complete record card. A simple enum might just have a name on the card, but a complex enum can have multiple labeled boxes: name, description, numeric code, category, and more—all bundled together.
Building Complex Enum State
Here's an enum modeling HTTP status codes with multiple fields:
public enum HttpStatus {
OK(200, "OK", true),
CREATED(201, "Created", true),
BAD_REQUEST(400, "Bad Request", false),
UNAUTHORIZED(401, "Unauthorized", false),
NOT_FOUND(404, "Not Found", false),
INTERNAL_ERROR(500, "Internal Server Error", false);
private final int code;
private final String message;
private final boolean isSuccess;
HttpStatus(int code, String message, boolean isSuccess) {
this.code = code;
this.message = message;
this.isSuccess = isSuccess;
}
public int getCode() { return code; }
public String getMessage() { return message; }
public boolean isSuccess() { return isSuccess; }
}
Each constant carries three related pieces of information. You can now write HttpStatus.NOT_FOUND.getCode() to get 404, or check status.isSuccess() to categorize responses.
Why This Matters
Complex enum state eliminates parallel arrays or lookup maps. Everything related to a constant lives with that constant, making your code self-documenting and type-safe.
Key Takeaway: Enums with multiple fields turn simple constants into rich data structures, bundling related information together for cleaner, more expressive domain modeling.