Course contentsShow
← Java
Lesson 587 of 2,87014. EnumerationsFree lesson

Declaring Fields in Enums

Learn how to add instance fields to enum constants to store additional data with each constant.

Declaring Fields in Enums

What you'll learn: How to add instance fields to each enum constant so that every constant can carry its own custom data.

The Core Idea

Just like regular classes, enums can have fields. Each enum constant can store its own values in these fields, making each constant more than just a name—it becomes a mini-object with properties.

Think of it like a menu at a restaurant. Each dish (enum constant) isn't just a name; it also has a price, calories, and preparation time. Those extra details are the fields.

How It Works

To add fields to an enum:

  1. Declare the field as you would in any class (usually private final)
  2. Create a constructor to initialize the field
  3. Pass values to the constructor when declaring each constant
  4. Add getter methods to access the field values

Here's a simple example:

public enum Day {
    MONDAY(true),
    TUESDAY(true),
    WEDNESDAY(true),
    THURSDAY(true),
    FRIDAY(true),
    SATURDAY(false),
    SUNDAY(false);

    private final boolean isWeekday;

    Day(boolean isWeekday) {
        this.isWeekday = isWeekday;
    }

    public boolean isWeekday() {
        return isWeekday;
    }
}

Now you can use it:

Day today = Day.SATURDAY;
System.out.println(today.isWeekday());  // false

Notice how each constant passes its specific value to the constructor. The enum constants are listed first, followed by the semicolon, then the fields and constructor like a normal class.

Key Takeaway: Enum fields let each constant store unique data, transforming enums from simple name lists into rich, data-carrying objects that combine type safety with custom properties.