Member-only story
Effective Java! Emulate Extensible Enums With Interfaces.
We continue digging into different considerations while working with enums
. Earlier in this series we considered the alternatives to the use of enum
s. 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 enum
s, 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 enum
s 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…