Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't Java allow enum to be defined within a method? [duplicate]

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.

like image 577
Priyank Doshi Avatar asked Jun 14 '12 04:06

Priyank Doshi


2 Answers

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;
    }
}
like image 155
Cole Tobin Avatar answered Sep 23 '22 17:09

Cole Tobin


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.

like image 28
Nishant Avatar answered Sep 22 '22 17:09

Nishant