I often stumble over ideas that are cool in some way and that I would never have thought about it. One of those ideas is extending Java Enums. Often frameworks and toolkits bring some kind of enumeration with them. For most of the tasks at hand, the elements in those Enums are sufficient. For the other cases, they can be extended to include more status. Of cause the library cannot handle the added elements in the Enum, so the methods working with it may have to be overridden. In this article I want to show how Java Enums can be extended.
First, let’s have a look at the Enum:
To make this Enum extendable, the following points must hold true:
- An extension-interface has to be delivered with the Enum. This interface defines all methods that the Enum and its extension should provide.
- The Enum has to implement that interface.
With that interface, an extension can be written:
As you can see, extending Enums is easy if the framework provides the interface for it. By either providing it or not, an API can be designed to have its Enums extended or not. As far as I see, there is no way to extend an Enum if there isn’t an interface for it within the API.
One weak point of that technique is that the user of the API has to implement the already existing elements of the Enum which causes code duplication.
Although this seems to be quite interesting, I have never seen this technique in the projects I worked in.