java - Enum method overriding -
i've found enums defined following:
public enum myenum { 1 { @override public int getsomething() { return 1; } }, 2 { @override public int getsomething() { return 2; } } int getsomething() { return 0; } } somehow feel type of discomfort implementation because think ideally field should defined purpose , class should like:
public enum myenum{ one(1), two(2) private int thesomething; private myenum(int something) { thesomething = something; } int getsomething() { return thesomething; } } the problem apart personal discomfort cannot find reason change code. exists?
(moved comment)
your first example used commonly implement finite state machine in java. eliminates need every method having have 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; } }
Comments
Post a Comment