Why does Java not allow enumeration in a method?

Possible duplicate:
Java: Local Enumerations

Why can't we define an enumeration in a specific method in java? If I have a scenario in which I will use these enumeration values ​​in a method, but not elsewhere. Wouldn't it be nice to state in a method that would rather define it globally? I mean as public or default.

+6
source share
3 answers

You cannot define at the method level as indicated by JavaDocs . (I would like to see the language that allowed this)

Nested enumeration types are implicitly static. It is permissible to explicitly declare a nested enumeration type static.

This means that it is not possible to define a local (Β§14.3) enumeration or to define an enumeration in an inner class (Β§8.1.3).

What you can do is declare it at the class level and 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; } } 
+7
source

from JLS

Nested enumeration types are implicitly static. It is permissible to explicitly declare a nested enumeration type static.

This means that it is not possible to define a local (Β§14.3) enumeration or to define an enumeration in an inner class (Β§8.1.3).

In addition, they are implicitly definitive, as a rule. This is a common template to have enumerations as part of a class, as a rule, they behave like a constant.

An enumeration type is implicitly final if it contains at least one enumeration constant that has the class body.

+3
source

You cannot define enumerations in methods, but you can define classes, so if you really want to create your method 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 } 
0
source

Source: https://habr.com/ru/post/918056/


All Articles