So I have my enum
public enum Sample {
ValueA{
@Override
public String getValue(){ return "A"; }
},
ValueB{
@Override
public String getValue(){ return "B"; }
public void doSomething(){ }
};
abstract public String getValue();
};
and I have some other code trying to use the enum.
Sample.ValueB.doSomething();
Which seems like it should be valid, but produces the error “The method doSomething() is undefined for the type Sample”. As opposed to
Sample value = Sample.ValueB;
value.doSomething();
which produces the same error and seems reasonable.
I assume there is a reasonable answer as to why the first one doesn’t work and it relates to the two examples being equivalent under the hood. I was hoping someone could point me towards the documentation on why it is that way.
The type of the “field”
ValueAisSample. That means that you can only invoke methods onValueAthatSampleprovides. From JLS §8.9.1. Enum Constants:More importantly: From a design perspective
enumvalues should be uniform: if some operation is possible with one specific value, then it should be possible with all values (although it might result in different code being executed).