Just another developer blog

Java enums can implement interfaces

Java enums can implement interfaces

Java enums are handy things. Often used as an effective replacement for simple int constants you can also add methods and fields and make them implement arbitrary interfaces.

Joshua Bloch has lots of interesting things to say about them in his excellent book, Effective JavaItem 34 describes a way to emulate extensible enums with interfaces but having an enum implement an interface can also be a simple way to split a large, unwieldy enum into smaller parts.

Consider a simple enum that contains a code and a message:

Perhaps you have hundreds of codes associated with different parts of your application but you want to do some common processing of them. Rather than maintaining a big enum full of all the codes in your system you could extract an interface and have your enums implement it. The enums could then be much smaller and placed with or near the code that uses them directly.

Here’s the Code interface:

Your smaller enums would implement it:

The only downside is you can’t share behaviour (at least no more than Java 8 allows for interfaces with default and static methods) but in this case it doesn’t matter because the amount of code is small.



Leave a Reply

Your email address will not be published. Required fields are marked *