I've found Enum
s defined like the following:
public Enum MyEnum {
ONE
{
@Override
public int getSomething() {
return 1;
}
},
TWO
{
@Override
public int getSomething() {
return 2;
}
}
int getSomething()
{
return 0;
}
}
Somehow I feel some type of discomfort with this implementation because I would think that ideally a field should be defined for this purpose and the class should look something like:
public Enum MyEnum{
ONE(1),
TWO(2)
private int theSomething;
private MyEnum(int something) {
theSomething = something;
}
int getSomething()
{
return theSomething;
}
}
The problem is that apart from personal discomfort I cannot find any good reason to change this code. Do any exists?
(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)
etcThe first pattern is slightly better for "default" methods that don't all need to be overridden.