Possible Duplicate:
Java: Local Enums
Why do we cannot define enum within a specific method in java? If I have a scenario where I will be using those enum values in a method only not at any other place. Wouldn't it be nice to declare in method rather defining it at globally? i mean as public or default.
You cannot define at the method level as stated by the JavaDocs. (I would like to see a language that allowed that)
Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.
This implies that it is impossible to define a local (§14.3) enum, or to define an enum in an inner class (§8.1.3).
What you can do it declare it at the class level and a variable at the method level:
public class Light {
...
private LightSwitch position;
private enum LightSwitch {
On,
Off
}
public void SwitchOn() {
Switch(LightSwitch.On);
}
public void SwitchOff() {
Switch(LightSwitch.Off);
}
private void Switch(LightSwitch pos) {
position = pos;
}
}
from JLS
Nested enum types are implicitly static. It is permissible to explicitly declare a nested enum type to be static.
This implies that it is impossible to define a local (§14.3) enum, or to define an enum in an inner class (§8.1.3).
Also, they are implicitly final, generally. It's general pattern to have enums as part of class as usually they behave as a constant.
An enum type is implicitly final unless it contains at least one enum constant that has a class body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With