Why can’t enums be declared locally in a method?

Enums are static nested classes because they define static member variables (the enum values), and this is disallowed for inner classes: http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.1.3

Update: I was looking through the JLS (java language specification) for more detail on the restrictions of static nested classes, and didn’t find it (although it’s probably there, hidden under a different topic). From a pure implementation perspective, there’s no reason that this couldn’t be done. So I suspect that it was a language philosophy issue: it shouldn’t be done, therefore won’t be supported. But I wasn’t there, so that’s pure speculation.

As a comment: if your methods are large enough that they require their own enums, then it’s a strong sign that you need refactoring.

Leave a Comment