How to reuse code in multiple Enum

enums, java, oop

Solution

Ah yes, this limitation has bitten me a couple of times. Basically, it happens whenever you have anything but the most trivial model on which you apply the enum.

The best way I found to work around this was a utility class with static methods that are called from your `aMethod`.

Problem

As we know that java enum class : - implicitly extends java.lang.Enum; - can't extends from any other enum classes. I have multiple enum class,like below: ``` enum ResourceState { RUNNING, STOPPING,STARTTING;//... void aMethod() { // ... } } enum ServiceState { RUNNING, STOPPING,STARTTING,ERROR;//... void aMethod() { // ... } } ``` the method `aMethod()` in enum `ResourceState` and `ServiceState` is exactly the same. in OOP,if `ResourceState` and `ServiceState` are not enum,they should abstract the same method to an super Abstract class,like this: ``` abstract class AbstractState{ void aMethod() { // ... } } ``` but ResourceState is unable to extends from AbstractState,Do you have any idea to work around?

Original source