Java tricks. Extending enumerations

Goal: 1) to have a type that represents a static set of constant values, so we can benefit from the compile-time check… or in less words, an Enum type, 2) to be able to extend the pre-defined set of values in the client class that extends a base client class… ideally, NewEnum extends BaseEnum.

Unfortunately, it’s not possible to extend enum type in Java, because of the enum nature: enum is an ordinal type, which makes it possible to be used in switch operator.

So the solution I’ve come up with is to introduce an interface. Let’s see how it works with the following example.

public interface State {
    String name(); // will be implemeted by java.lang.Enum class
}

public class Entity {
    private State state = ObjectState.CREATED;
    public void setState(State state) { this.state = state; }
    public State getState() { return state; }

    public enum ObjectState implements State {
        CREATED, ACTIVE, DELETED
    }
}

public class Order extends Entity {
    public enum OrderState implements State {
        ACCEPTED, DELIVERED, CANCELLED
    }
}

public class EntityController {
    public void create(Entity entity) { entity.setState(ObjectState.CREATED); }
    public void delete(Entity entity) { entity.setState(ObjectState.DELETED); }
    public void activate(Entity entity) { entity.setState(ObjectState.ACTIVE); }
}

public class OrderController extends EntityController {
    public void accept(Order order) { order.setState(OrderState.ACCEPTED); }
    public void deliver(Order order) { order.setState(OrderState.DELIVERED); }
    public void cancel(Order order) { order.setState(OrderState.CANCELLED); }
}

Pros: both goals achieved, namely we’ve got static constant values and we are not limited by a pre-defined set of values, we can extend it for future use cases.
Cons: there’s no real extensibility of base enum, so we should be aware of the existing base enum before ‘extending’ it, so we don’t repeat values from it.

  • http://www.extended-enums.org Chris May

    Hi all,

    the missing extendability of enumerations is a recurring (and pretty much arbitrary) limitation of the Java language, and for many instances a royal pain (especially in combination with annotations).

    We are joining forces to propose at least a basic support for enumeration extendability for the upcoming Java-8 edition. This would be a minimal change with a maximum of impact and transcendence.

    Please help us in moving the Extended-Enum petition forward, and vote for us at http://www.extended-enums.org

    cheers and thnx,

    Chris

  • admin

    Hi Chris,

    Thanks for sharing. I support the initiative and will definitely vote for it. Will also spread the word.

    Cheers,

    Vlad