is there a simple way to subclass a Java enum
?
I ask this because I have like 10 of them that implement the same interface but they also have the same implementation for some methods so I would like to reuse the code by placing all the same implementations in middle object that extends Enum
and it is also the superclass of all the others I need.
Maybe it is not so straightforward as I think?
Thank in advance
Whilst there have been proposals for abstract enums in Java, the benefits are considered far too low to outweigh the costs. You'll have to stick with forwarding method calls.
The language does not allow you to do so, as Enums are designed for representing enumerated values efficiently, not for implementing code. Try using another pattern like a static helper (utility) class.
You can't do it, since the language does not allow you. And for a good logical reason: subclassing an enum would only make sense if you could remove some enum values from the subclass, not add new ones. Otherwise you would break the Liskov Substitution Principle.
This in brief states that every instance of a subclass should be acceptable whenever an instance of a superclass is expected. If you add a new enum member in an enum subclass, that clearly can't be accepted by someone knowing only the super enum.
For more details and possible alternatives, see this earlier answer of mine.
In your concrete case, @Jason's suggestion may offer a good solution (+1 for him :-)
Update to @OrangeDog's comment
Good point, I was a bit sloppy above :-) Implementation-wise you are right. However, from the logical point of view an enum type is fully described by the set of its valid values. And generally, a proper subclass is a specialization of its superclass. In other words, the set of valid subclass instances is (should be) always a subset of the superclass instance set. (Every dog is an animal, but not every animal is a dog.)
With Java 8 you can put the shared implementation in the interface using default methods.
If access to methods implemented by the
Enum
class is required, add the signature to the interface:@Jason S has offered a good reply, but the static method make you lose the OOP's potentialities.
What about delegation? I mean:
Define a common interface "I_A" where you defines all getters/setters and all other methods.
Define a "struct-like" class "S_C" : it implements only the getters and setters, other methods are empty because are useless.
To make your enumerations shorter (in terms of lines of code), define a second interface "I_A_Delegating" that extends the first ones, has an additional getter/setter of type "I_A" (it's our delegator) and, thanks to Java's default methods, define the getter/setter as calling the delegator's getter/setter.
All of your enumerations implements "I_A_Delegating" and has a local instance of "S_C"
Code example:
How about using a static helper class?