Enums with interfaces
I had an idea for a way to clean up some code today. I tried to implement the solution I thought up, but was left scratching my head instead. For some reason I thought it would be simple to create an enum with another enum inside the first. For example, say you have an enum that is Supper. Supper has values of STARTER, MAIN_COURSE and PUDDING. Inside of value STARTER would be another set of enum values, E.g. MELON, SOUP, etc. In order to get to SOUP you would then write, Supper.STARTER.SOUP. However as I soon found out, it’s not possible, which is a little disappointing, but I can see why. You can have one of the enum constant values inside of the constructor of another enum, but not the enum itself. E.g. STARTER(Starter.SOUP), but not STARTER(Starter).
So what could I use as alternative?
Well I then mocked up a simple alternative that makes use of an interface for the enums. Instead of having a parent enum Supper, there is now an interface ISupper with a single method
getValue()
. Two enums then implement that interface, MainCourse and Starter. A simple method takes an instance of ISupper and calls the
getValue()
method, printing it to the console. Overall it’s not bad, looks neat and still achieves what I originally wanted.
So in total we have the following nums, class and interface:
ISupper.java
public interface ISupper
{
public String getValue();
}
Starter.java
public enum Starter implements ISupper
{
SOUP("Evens"), MELON("Melon with Parma Ham");
private String value;
private Starter(final String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
}
MainCourse.java
public enum MainCourse implements ISupper
{
CARBONARA("Chicken Carbonara"), SCOTCH_EGGS("Scotch Eggs");
private String value;
private MainCourse(final String value)
{
this.value = value;
}
public String getValue()
{
return value;
}
}
OrderExample.java
public class OrderExample
{
public static void main(final String... args)
{
print(Starter.MELON);
print(MainCourse.CARBONARA);
}
private static void print(final ISupper supper)
{
System.out.println(supper.getValue());
}
}
Please enable the Disqus feature in order to add comments