All 15 Enums questions
More in Enums
Advertisement
Back to results for “Design Patterns in Java”
Java › Enums

How would you implement an enum that also implements an interface, and what's the benefit of having different enum constants provide different behavior through a shared interface contract?

Intermediate

Answer

An enum can implement one or more interfaces just like a regular class, either providing a single shared implementation for all constants, or combined with constant-specific method bodies to give each constant its own distinct implementation of the interface's methods -- this is useful when you want the type-safety and exhaustiveness benefits of an enum while still being able to pass enum constants around polymorphically wherever the interface type is expected, integrating enums cleanly into broader interface-based designs.
public interface Discount {
    double apply(double price);
}

public enum DiscountType implements Discount {
    NONE { public double apply(double price) { return price; } },
    PERCENT_10 { public double apply(double price) { return price * 0.9; } },
    FLAT_5 { public double apply(double price) { return Math.max(0, price - 5); } };
}

Discount discount = DiscountType.PERCENT_10;  // usable polymorphically anywhere a Discount is expected
System.out.println(discount.apply(100.0));
Real-world example A pricing engine defines DiscountType as an enum implementing a shared Discount interface, letting checkout code accept any Discount polymorphically (whether it's a fixed enum constant or, in theory, some other non-enum Discount implementation), while still getting the enum's built-in enumeration and switch-exhaustiveness benefits for the fixed set of standard discount types.

Common follow-ups: Can an enum implement multiple interfaces simultaneously, given it can't extend multiple classes?;How does this pattern compare to the constant-specific-method-body Strategy pattern example without an explicit interface?