Extending Java Enums

I often stumble over ideas that are cool in some way and that I would never have thought about it. One of those ideas is extending Java Enums. Often frameworks and toolkits bring some kind of enumeration with them. For most of the tasks at hand, the elements in those Enums are sufficient. For the other cases, they can be extended to include more status. Of cause the library cannot handle the added elements in the Enum, so the methods working with it may have to be overridden. In this article I want to show how Java Enums can be extended.

First, let’s have a look at the Enum:

package closedLibrary;

public enum ClosedEnum implements ClosedEnumExtensionInterface {

	ONE(1), TWO(2);

	private int value;

	ClosedEnum(int value) {
		this.value = value;
	}

	public int getValue() {
		return value;
	}
}

To make this Enum extendable, the following points must hold true:

  1. An extension-interface has to be delivered with the Enum. This interface defines all methods that the Enum and its extension should provide.
  2. The Enum has to implement that interface.
package closedLibrary;

public interface ClosedEnumExtensionInterface {

	public int getValue();

}

With that interface, an extension can be written:

package ownProject;

import closedLibrary.ClosedEnumExtensionInterface;

public enum OwnExtendedEnum implements ClosedEnumExtensionInterface {

	ONE(1), TWO(2), THREE(3), FOUR(4);

	private int value;

	private OwnExtendedEnum(int value) {
		this.value = value;
	}

	@Override
	public int getValue() {
		return value;
	}
}

As you can see, extending Enums is easy if the framework provides the interface for it. By either providing it or not, an API can be designed to have its Enums extended or not. As far as I see, there is no way to extend an Enum if there isn’t an interface for it within the API.

One weak point of that technique is that the user of the API has to implement the already existing elements of the Enum which causes code duplication.

Although this seems to be quite interesting, I have never seen this technique in the projects I worked in.