0Pricing
Java Academy · Lesson

Enums with Fields and Methods

Add fields, constructors, and methods to enums to encapsulate behavior.

Enums with Fields and Methods is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Enums with Fields and Methods

Enum constants can carry data. You add fields by declaring them and a constructor. The constructor is automatically private.

Declaring Fields in Enums

Each enum constant calls the constructor when the class loads. Field values are set once and are immutable (when declared final).

enum Planet {
    MERCURY(3.303e+23, 2.4397e6),
    VENUS  (4.869e+24, 6.0518e6),
    EARTH  (5.976e+24, 6.37814e6),
    MARS   (6.421e+23, 3.3972e6);

    private final double mass;    // kilograms
    private final double radius;  // meters

    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }

    public double mass()   { return mass; }
    public double radius() { return radius; }
}

Adding Methods to Enums

Enum types can contain any methods you would put in a class, including computed properties.

enum Planet {
    EARTH(5.976e+24, 6.37814e6);
    // ... constructor and fields ...
    static final double G = 6.67300E-11;

    public double surfaceGravity() {
        return G * mass / (radius * radius);
    }

    public double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
}

double earthWeight = 75.0;
double mass = earthWeight / Planet.EARTH.surfaceGravity();
for (Planet p : Planet.values())
    System.out.printf("Weight on %s: %.2f%n", p, p.surfaceWeight(mass));

Abstract Methods on Enum Constants

Each constant can provide its own implementation of an abstract method declared in the enum body.

enum Operation {
    PLUS  { public double apply(double x, double y) { return x + y; } },
    MINUS { public double apply(double x, double y) { return x - y; } },
    TIMES { public double apply(double x, double y) { return x * y; } },
    DIVIDE{ public double apply(double x, double y) { return x / y; } };

    public abstract double apply(double x, double y);
}

System.out.println(Operation.PLUS.apply(3, 4));   // 7.0
System.out.println(Operation.TIMES.apply(3, 4));  // 12.0

String-Labeled Enums

A common pattern: give each constant a human-readable label stored as a field.

enum UserRole {
    GUEST("Guest User"),
    MEMBER("Registered Member"),
    ADMIN("Administrator"),
    SUPERADMIN("Super Administrator");

    private final String label;

    UserRole(String label) { this.label = label; }

    public String label() { return label; }

    public static UserRole fromLabel(String lbl) {
        for (UserRole r : values())
            if (r.label.equalsIgnoreCase(lbl)) return r;
        throw new IllegalArgumentException(lbl);
    }
}

System.out.println(UserRole.ADMIN.label()); // Administrator

Enum with Multiple Fields

Enums can have as many fields as needed. Here a currency enum stores both ISO code and symbol.

enum Currency {
    USD("US Dollar", "$"),
    EUR("Euro", "\u20ac"),
    GBP("British Pound", "\u00a3"),
    JPY("Japanese Yen", "\u00a5");

    public final String name;
    public final String symbol;

    Currency(String name, String symbol) {
        this.name = name;
        this.symbol = symbol;
    }

    public String format(double amount) {
        return String.format("%s%.2f", symbol, amount);
    }
}

System.out.println(Currency.EUR.format(99.99)); // \u20ac99.99

Overriding toString()

Override toString() in an enum to return a custom string representation instead of the constant name.

enum HttpMethod {
    GET, POST, PUT, PATCH, DELETE;

    @Override
    public String toString() {
        return name().toUpperCase();
    }

    public boolean hasBody() {
        return this == POST || this == PUT || this == PATCH;
    }
}

HttpMethod m = HttpMethod.POST;
System.out.println(m);            // POST
System.out.println(m.hasBody());  // true
System.out.println(HttpMethod.GET.hasBody()); // false

Enum with Validation

Enum constructors can validate their arguments to prevent invalid states.

enum DiscountTier {
    BRONZE(5), SILVER(10), GOLD(20), PLATINUM(30);

    public final int percentage;

    DiscountTier(int percentage) {
        if (percentage < 0 || percentage > 100)
            throw new IllegalArgumentException("Invalid: " + percentage);
        this.percentage = percentage;
    }

    public double apply(double price) {
        return price * (1 - percentage / 100.0);
    }
}

System.out.println(DiscountTier.GOLD.apply(100.0)); // 80.0

Enum Singleton Pattern

A single-constant enum is the safest way to implement a Singleton in Java — it is serialization-safe and thread-safe by default.

enum AppConfig {
    INSTANCE;

    private String dbUrl = "jdbc:postgresql://localhost/mydb";
    private int maxConnections = 20;

    public String getDbUrl() { return dbUrl; }
    public int getMaxConnections() { return maxConnections; }

    public void setDbUrl(String url) { this.dbUrl = url; }
}

// Access the singleton
AppConfig config = AppConfig.INSTANCE;
System.out.println(config.getDbUrl());

Enum in Domain Models

Enums are widely used in domain models to represent type-safe categories: order status, payment method, notification type, etc.

enum PaymentMethod {
    CREDIT_CARD("Credit Card", true),
    DEBIT_CARD("Debit Card", true),
    PAYPAL("PayPal", false),
    CRYPTO("Cryptocurrency", false),
    BANK_TRANSFER("Bank Transfer", false);

    public final String displayName;
    public final boolean instantCharge;

    PaymentMethod(String displayName, boolean instantCharge) {
        this.displayName = displayName;
        this.instantCharge = instantCharge;
    }
}

Enum Field vs Computed

Fields store fixed data; methods compute dynamic values. Use fields for constant data, methods for derived values.

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

    private final boolean weekend;
    DayType(boolean weekend) { this.weekend = weekend; }

    public boolean isWeekend()  { return weekend; }
    public boolean isWeekday()  { return !weekend; }

    public static long weekdayCount() {
        return java.util.Arrays.stream(values())
            .filter(DayType::isWeekday).count();
    }
}
System.out.println(DayType.weekdayCount()); // 5

Quick Check

How is an enum constructor different from a regular class constructor?

Recap: Enums with Fields and Methods

Key takeaways:

  • Add fields and a constructor to carry data per constant
  • Enum constructors are implicitly private
  • Abstract methods let each constant provide its own implementation
  • Override toString() for custom display names
  • Single-constant enums are the best Singleton implementation
  • Enums integrate naturally into domain models as type-safe categories

Frequently asked questions

Is the “Enums with Fields and Methods” lesson free?

Yes — the full text of “Enums with Fields and Methods” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Enums with Fields and Methods”?

Add fields, constructors, and methods to enums to encapsulate behavior. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Enums with Fields and Methods” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Defining and Using Enums
  2. Enums with Fields and Methods
  3. Switch Expressions with Enums
  4. EnumSet and EnumMap
← Back to Java Academy