Senior
Can an enum implement an interface?
sobes.tech AI
Answer from AI
Yes, in Java, an enum can implement an interface. This allows defining a set of methods that must be implemented by each enum element, ensuring polymorphism.
Example:
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; }
};
}
Thus, each enum element implements the interface method, allowing the enum to be used as a set of strategies or operations.