Java enums can implement interfaces

Leave a comment
Dev

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 Java. Item 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:

public enum Code {
    
    CODE_A("alpha"),
    CODE_B("bravo"),
    CODE_Y("yankee"),
    CODE_Z("zulu");

    private final String message;

    public String getMessage() {
        return 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:

public interface Code {
    String getMessage();
}

Your smaller enums would implement it:

public enum EarlyCode implements Code {
    CODE_A("alpha"),
    CODE_B("bravo");

    private final String message;

    @Override
    public String getMessage() {
        return message;
    }
}

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 *