From another question I have learnt that it is possible in Java to define specific methods for each one of the instances of an Enum:
public
You need to declare abstract methods in your enum which are then implemented in specific enum instances.
class Outer {
private enum MyEnum {
X {
public void calc(Outer o) {
// do something
}
},
Y {
public void calc(Outer o) {
// do something different
// this code not necessarily the same as X above
}
},
Z {
public void calc(Outer o) {
// do something again different
// this code not necessarily the same as X or Y above
}
};
// abstract method
abstract void calc(Outer o);
}
public void doCalc() {
for (MyEnum item : MyEnum.values()) {
item.calc(this);
}
}
}
Each enum
is an anonymous inner class. So like any anonymous inner class, you can add all of the methods you want, but there is no way to reference them outside of the class, as the class doesn't have a type that defines the methods.
The advantage of allowing methods on the enum
implementation is that it allows for a strategy pattern, where the enum itself has an abstract method or a default implementation, and specific members of the enum
have implementations of that method that may do something different.
I have used this technique to greatly reduce code complexity on switch statements. Instead of switching on the enum in some other class, just get a reference to it and call a method, and let the enum itself take care of it. Of course that depends on the scenario if it makes sense, but it can reduce code complexity tremendously.
You cannot refer to those methods, because you are effectively creating anonymous (*) class for each enum. As it is anonymous, you can reference such methods only from inside your anonymous class itself or through reflection.
This technique is mostly useful when you declare abstract method in your enumeration, and implement that method for each enum individually.
(*) JLS 8.9 Enums part says: "The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type."