Member-only story

Effective Java! Emulate Extensible Enums With Interfaces.

Kyle Carter
3 min readJun 3, 2021

We continue digging into different considerations while working with enums. Earlier in this series we considered the alternatives to the use of enums. Throughout the preceding chapters we have shown that enums are the preferred method. There is one place where the alternatives of using regular classes are superior to enums, that is with extending existing functionality. For good reason the enum type does not allow extension.

That being said, there are times when we could want this type of functionality, particularly when working with enums that represent different operations. In a previous chapter we saw this use case with our Calculator class and taking the Operation enum. Luckily there is a way to mimic the extension behavior via interfaces. Let's look at what this would look like with our Operation enum.

public interface Operation {
double apply(double x, double y);
}
public enum BasicOperation implements 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; }
};
private final String symbol; BasicOperation(String symbol) {
this.symbol = symbol;
}
@Override
public String toString() {
return

--

--

Kyle Carter
Kyle Carter

Written by Kyle Carter

I'm a software architect that has a passion for software design and sharing with those around me.

No responses yet