Enum method overriding
(moved from comment)
Your first example is used commonly to implement a finite state machine in Java. It eliminates the need for every method having to have a if (state == FOO) {} else if (state == BAR)
etc
class MyFSM {
enum State {
FIRST_STATE {
@Override
void start(MyFSM fsm) {
fsm.doStart();
}
@Override
void stop(MyFSM fsm) {
throw new IllegalStateException("Not Started!");
}
},
SECOND_STATE {
@Override
void start(MyFSM fsm) {
throw new IllegalStateException("Already Started!");
}
@Override
void stop(MyFSM fsm) {
fsm.doStop();
}
};
abstract void start(MyFSM fsm);
abstract void stop(MyFSM fsm);
}
private volatile State state = State.FIRST_STATE;
public synchronized void start() {
state.start(this);
}
private void doStart() {
state = SECOND_STATE;
}
public synchronized void stop() {
state.stop(this);
}
private void doStop() {
state = FIRST_STATE;
}
}
The first pattern is slightly better for "default" methods that don't all need to be overridden.
public enum Modes {
MODE_ONE {
@Override public boolean canDoA() {
return true;
}
},
MODE_TWO {
@Override public boolean canDoB() {
return true;
}
},
MODE_THREE {
@Override public boolean canDoC() {
return true;
}
};
public boolean canDoA() {
return false;
}
public boolean canDoB() {
return false;
}
public boolean canDoC() {
return false;
}
}