Extensible Java Enum.

As you know you can’t extend Enum in Java in order to add a new enumeration value since they are final. But what about the case that you want to use that enum in your code but at the same time allow additional values to be represented by that enum type. For example lets take a very simple ENUM that defines some type of EVENT:

Here you can see that we wont be able to introduce additional EVENTS without modifying the EventTypes enum. This will become an issue when we dont control all EVENT types, for example in case when they are passed to us from external system.

To solve this issue we will leverage the fact that enums can implement interfaces by declaring a parent interface that our EventTypes enum will implement and changing the handleEvent method to take object of that interface type instead of EventTypes.
Here is the revised code:

Now we are not bound to any particular enum and at the same time use Enum “==” operator to check if event is of a particular enum type. And the sendEvent method can pass both EventTypes1 and EventTypes2 enums to the same handleEvent method.

But we can extend this even further and have “handleEvent” method(s) that will work on any type of EVENTS without extending existing enums or defining a new ones.
Here is the final revised code:

Finally, as a best practice, in most cases it would make sense to use interface type for public method argument or return type instead of particular enum.

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>