Sub topic 6
Enums That Implement Interfaces
In earlier chapters you gave enum constants fields, constructors, methods, and even their own method bodies. This chapter adds one more ability. An enum can implement an interface, just like a regular class can.
An interface is a list of methods that a type promises to provide. When a type implements an interface, other code can work with it through that interface without knowing the exact type behind it.
Why would an enum need this? Here are three common reasons:
- You want several unrelated types, including enums, to share one method name such as
label(). - You want code that works with "any operator" and not only the constants of one enum.
- You want to pass enum constants to Java library methods that expect a standard interface, such as
IntBinaryOperator.
The Basic Syntax
You write implements after the enum name, before the opening brace. Then the enum must supply every method the interface declares.
interface Labeled {
String label();
default String describe() {
return "[" + label() + "]";
}
}
enum Size implements Labeled {
SMALL("S"), MEDIUM("M"), LARGE("L");
private final String label;
Size(String label) {
this.label = label;
}
@Override
public String label() {
return label;
}
}
public class Main {
public static void main(String[] args) {
for (Size s : Size.values()) {
System.out.println(s + " -> " + s.label() + " " + s.describe());
}
Labeled thing = Size.MEDIUM;
System.out.println(thing.label());
}
}Running this prints:
SMALL -> S [S]
MEDIUM -> M [M]
LARGE -> L [L]
MA few things to notice:
Sizestores its label in a field, as you learned before. Thelabel()method returns that field.- The
label()method is markedpublic. Every method in an interface is public, so the method that implements it must be public too. describe()is a default method. A default method is an interface method that already has a body.Sizegets it for free without writing any code.- The line
Labeled thing = Size.MEDIUM;works because everySizeconstant is aLabeled. The variable only knows about the interface methods.
One Interface, Many Enums
Suppose you build a small calculator. You want basic operators and, later, some extra ones. An enum cannot be extended, so you cannot write a second enum that "adds constants" to the first one. An interface solves this. Both enums implement the same interface, and your calculator code talks only to the interface.
import java.util.ArrayList;
import java.util.List;
interface Operator {
int apply(int a, int b);
String symbol();
}
enum BasicOperator implements Operator {
PLUS("+") {
public int apply(int a, int b) { return a + b; }
},
MINUS("-") {
public int apply(int a, int b) { return a - b; }
};
private final String symbol;
BasicOperator(String symbol) {
this.symbol = symbol;
}
public String symbol() {
return symbol;
}
}
enum ExtraOperator implements Operator {
TIMES("*") {
public int apply(int a, int b) { return a * b; }
},
MAX("max") {
public int apply(int a, int b) { return Math.max(a, b); }
};
private final String symbol;
ExtraOperator(String symbol) {
this.symbol = symbol;
}
public String symbol() {
return symbol;
}
}
public class Calculator {
static void printAll(List<Operator> ops, int a, int b) {
for (Operator op : ops) {
System.out.println(a + " " + op.symbol() + " " + b + " = " + op.apply(a, b));
}
}
public static void main(String[] args) {
List<Operator> ops = new ArrayList<>();
ops.addAll(List.of(BasicOperator.values()));
ops.addAll(List.of(ExtraOperator.values()));
printAll(ops, 6, 3);
}
}Output:
6 + 3 = 9
6 - 3 = 3
6 * 3 = 18
6 max 3 = 6Look at how apply is handled. Neither enum writes apply at the enum level. Each constant gives its own body instead, using the constant-specific bodies from the previous chapter. Java accepts this because every single constant supplies the method. If you removed the body from MINUS, the program would not compile.
The symbol() method works differently. It is written once at the enum level and shared by all constants of that enum.
The printAll method never mentions BasicOperator or ExtraOperator. It only knows Operator. You could add a third enum next month without changing printAll at all.
Implementing a Standard Java Interface
The Java library has many ready-made interfaces. One of them is IntBinaryOperator from the package java.util.function. It has one method, applyAsInt(int left, int right), which takes two numbers and returns one. Many library methods accept it.
If your enum implements IntBinaryOperator, you can hand its constants straight to those library methods. This version stores a lambda in each constant. A lambda is a short way to write a small function, like (a, b) -> a + b.
import java.util.function.IntBinaryOperator;
import java.util.stream.IntStream;
enum MathOp implements IntBinaryOperator {
ADD((a, b) -> a + b),
MULTIPLY((a, b) -> a * b),
MIN(Math::min);
private final IntBinaryOperator function;
MathOp(IntBinaryOperator function) {
this.function = function;
}
@Override
public int applyAsInt(int left, int right) {
return function.applyAsInt(left, right);
}
}
public class Main {
public static void main(String[] args) {
System.out.println(IntStream.of(1, 2, 3, 4).reduce(0, MathOp.ADD)); // 10
System.out.println(IntStream.of(1, 2, 3, 4).reduce(1, MathOp.MULTIPLY)); // 24
System.out.println(IntStream.of(7, 2, 9).reduce(Integer.MAX_VALUE, MathOp.MIN)); // 2
}
}reduce combines the numbers one pair at a time using the operator you give it. It expects an IntBinaryOperator, and MathOp.ADD is one. Math::min is a method reference, another short way to write a lambda that just calls an existing method.
This style is an alternative to constant-specific bodies. Both work. The lambda style is shorter when each behavior fits on one line.
| Style | How each constant gets behavior | Good when |
|---|---|---|
| Shared method | One method at the enum level reads a field | All constants behave the same way, only data differs |
| Constant-specific body | Each constant writes `{ public int apply(...) { ... } }` | Behaviors are a few lines long and differ a lot |
| Lambda in constructor | Each constant passes a function to the constructor | Behaviors are tiny one-liners |
Gotchas and Edge Cases
Enums cannot use `extends`
Every enum already extends a built-in class called java.lang.Enum. Java allows only one parent class, so this is illegal:
enum Size extends SomeClass { ... } // compile errorInterfaces are the way to share a type across enums. An enum may implement several interfaces at once, separated by commas: enum Size implements Labeled, Comparable<...>. In practice you rarely add Comparable yourself, as the next point explains.
Some interfaces are already implemented
Every enum automatically implements Comparable and Serializable. Constants compare by their declaration order (their ordinal). The compareTo method is final in java.lang.Enum, so you cannot change how enums sort. If you need a different order, use a separate Comparator.
Forgetting `public`
This is the most common beginner error:
enum Size implements Labeled {
...
String label() { return label; } // error: weaker access privileges
}Interface methods are public. Leaving out public makes the method package-private, which is "weaker", and the compiler rejects it. The same rule applies inside constant-specific bodies, which is why apply in BasicOperator is marked public.
Through the interface, you lose enum features
A variable of type Operator only offers apply and symbol. It has no values(), valueOf(), or ordinal(). Those belong to each enum type. That is why the calculator collects constants by calling BasicOperator.values() and ExtraOperator.values() directly.
Every constant must be complete
If the enum does not implement an interface method itself, every constant must provide a body for it. Miss one constant, and compilation fails. This check helps you: you cannot forget to give a new constant its behavior.
When to Use This
Reach for an interface on an enum when:
- other code should accept "anything that can do X", and some of those things are enum constants;
- you want a set of constants that others can add to by writing their own enum;
- a library method expects a standard interface and your constants fit it.
If only one enum will ever exist and nobody outside needs a shared type, plain enum methods are simpler. Do not add an interface just because you can.
Exercise
Write an interface Greeter with one method String greet(String name). Then write an enum Language with constants ENGLISH and SPANISH that implements Greeter, so that Language.ENGLISH.greet("Ana") returns "Hello, Ana" and Language.SPANISH.greet("Ana") returns "Hola, Ana". Use a field and one shared method.
Show answer
interface Greeter { String greet(String name); } enum Language implements Greeter { ENGLISH("Hello"), SPANISH("Hola"); private final String word; Language(String word) { this.word = word; } @Override public String greet(String name) { return word + ", " + name; } }. The field stores the greeting word, and the single public greet method builds the text for every constant.
Exercise
A student writes enum Level implements Labeled { LOW, HIGH; String label() { return name().toLowerCase(); } } and gets a compile error. What is wrong, and how do you fix it?
Show answer
The method label() implements an interface method, and interface methods are public. Without the public keyword the method has package-private access, which is weaker, so the compiler rejects it. Fix it by writing public String label() { ... }, ideally with @Override above it.
Exercise
You have a variable Operator op = BasicOperator.PLUS;. Can you call op.ordinal()? Explain why or why not, and say how you would get the ordinal.
Show answer
No. The variable's type is the Operator interface, which only declares apply and symbol, so the compiler does not allow ordinal() on it. The object really is an enum constant, so you can call BasicOperator.PLUS.ordinal() directly, or check with if (op instanceof BasicOperator b) and then call b.ordinal().