Other Answers are outmoded as of Java 16 (released 2021-03) and Java 17 (released 2021-09).
Local enums in Java 16+
As part of the records feature introduced in Java 16, enums may now be defined locally. Indeed, records, enums, and interfaces can all be local now.
To quote JEP 395:
The ability to declare local record classes, local enum classes, and local interfaces was introduced.
…
The addition of local record classes is an opportunity to add other kinds of implicitly-static local declarations.
Nested enum classes and nested interfaces are already implicitly static, so for consistency we define local enum classes and local interfaces, which are also implicitly static.
You can now run the following example code to use an enum defined within a method.
private void demoLocalEnum ( )
{
enum Color { PURPLE, SAFETY_ORANGE }
System.out.println( Color.PURPLE );
}
In this screenshot, we can see how the local enum exists only within its defining method. A sibling method cannot see that enum. Trying to call that enum from another method generates an error.
See a demo of such code running in the IntelliJ 2020.2 IDE.
Implicitly static
There is one limitation with a locally defined enum: No access to state in surrounding class.
Example code:
private void demoLocalEnum ()
{
int x = 42;
enum Color
{
PURPLE,
SAFETY_ORANGE;
public void demo ()
{
System.out.println( "Now is " + Instant.now() ); // This line works.
System.out.println( "x = " + x ); // ERROR — Non-static variable 'x' cannot be referenced from a static context.
}
}
Color.PURPLE.demo();
}
My IntelliJ IDE reports error:
Non-static variable 'x' cannot be referenced from a static context
As mentioned in the JEP 395 quote above, a local enum is implicitly static
. So any methods you may define on your local enum cannot access state on the surrounding outer class.
To quote JEP 395, regarding local records but applying to local enums as well:
Local record classes are a particular case of nested record classes. Like nested record classes, local record classes are implicitly static. This means that their own methods cannot access any variables of the enclosing method; in turn, this avoids capturing an immediately enclosing instance which would silently add state to the record class. The fact that local record classes are implicitly static is in contrast to local classes, which are not implicitly static. In fact, local classes are never static — implicitly or explicitly — and can always access variables in the enclosing method.