0Pricing
Java Academy · Lesson

Abstract Methods in Enums

Per-constant behavior.

Per-Constant Behavior

Sometimes each enum constant needs different behavior, not just different data.

Java lets you declare an abstract method on the enum and override it for each constant. This is the constant-specific method body pattern.

public class Main {
    enum Operation {
        PLUS { public int apply(int a, int b) { return a + b; } },
        MINUS { public int apply(int a, int b) { return a - b; } };
        public abstract int apply(int a, int b);
    }
    public static void main(String[] args) {
        System.out.println(Operation.PLUS.apply(3, 4));
        System.out.println(Operation.MINUS.apply(10, 6));
    }
}

How It Works

Each constant with a body becomes an anonymous subclass of the enum.

The abstract method forces every constant to provide an implementation, so the compiler guarantees completeness.

public class Main {
    enum Operation {
        TIMES { public int apply(int a, int b) { return a * b; } };
        public abstract int apply(int a, int b);
    }
    public static void main(String[] args) {
        // The constant is an instance of a generated subclass
        System.out.println(Operation.TIMES.getClass().getSimpleName().isEmpty()
            ? "anonymous subclass" : Operation.TIMES.apply(6, 7));
    }
}

All lessons in this course

  1. Enums with Fields and Methods
  2. Abstract Methods in Enums
  3. EnumSet
  4. EnumMap
← Back to Java Academy