Jamie's Blog

Ruby developer. CTO. Swimmer. Always trying to write more

Enums, Interfaces and Method Implementations

Sorry, this is a slightly technical post… please ignore if you don’t read Java.

All Java programmers know that method implementation can’t appear interfaces. Basically, the interface let you define constants and method declarations but you need to put the implementation into a class which implements that interface. Well, that was true until Java 5.

Java 5 introduced type-safe enums as a new means of providing constant values, e.g.

public enum COLOURS {RED, BLUE, GREEN};
Since enums are providing constant values they are often placed in interfaces. However, enums can also be extended with methods (typically to convert between values):
public enum COLOURS {
    public String toCSS(){
            case RED:
            return "#ff0000";

        case GREEN:
        return "#00ff00";

        case BLUE:
        return "#0000ff";


And, this form is still accepted within an interface. It works because the method is basically operating as a static method with a restricted scope but it’s still slightly surprising to see actual implementation code in an interface.