9

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.

Community
  • 1
  • 1
Priyank Doshi
  • 12,895
  • 18
  • 59
  • 82
  • Jon Skeet said that [enums are implicitly static](http://stackoverflow.com/a/4827347/348975). – emory Jun 14 '12 at 04:30
  • **Update:** Local enums, defined within a method, will be a feature in Java 16, previewing in Java 15. See: [*JEP 384: Records (Second Preview)*](https://openjdk.java.net/jeps/384). Discussed in [my Answer](https://stackoverflow.com/a/62807591/642706) on another page. – Basil Bourque Jul 09 '20 at 05:03

3 Answers3

7

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;
    }
}
Cole Tobin
  • 9,206
  • 15
  • 49
  • 74
3

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.

Nishant
  • 54,584
  • 13
  • 112
  • 127
0

You cannot define enums within methods, but you can define classes, so if you really wish to design your method in this way, you can define an array of your local class object.

public void doSomething() {
    class Country {
        int population = 0;
        String name = null;

        public Country(int population, String name) {
            this.population = population;
            this.name = name;
        }

    }
    Country[] countries = { new Country(85029304, "Germany"), new Country(61492053, "Spain") };
    // do stuff with countries
}
FThompson
  • 28,352
  • 13
  • 60
  • 93