Consider the simple example below of implementing a method in an Enum. One problem with this method is that, when you have a lot of enum instances, you visually can no longer see them all at once, as a list. That is, if we had many toys, I would like to see “DOLL, SOLDIER, TEDDYBEAR, TRAIN, ETC”, together, in one long list, and then after that list I could implement any needed methods, e.g. methods that are abstract in the enum itself.
Is there any way to do this? Or do you have to implement the methods when you declare the individual enum instances, as in the example below?
public enum Toy {
DOLL() {
@Override public void execute() {
System.out.println("I'm a doll.");
}
},
SOLDIER() {
@Override public void execute() {
System.out.println("I'm a soldier.");
}
};
//abstract method
public abstract void execute();
}
One way that comes to mind is to leave the implementation of the abstract methods to separate implementation classes, something like:
This setup would allow you to create behaviour classes in separate files in the case that your implementation has enough complexity to warrant separation.
In the case that the implementation is simple enough to include it into the one
enumclass, you can put the interface and behaviour classes as children of the enum class:I would probably opt for the first implementation myself, unless the hierarchy of implementation classes is very trivial.