7

I am studying Java and wrote a very simple program. In it I can put enums in the top most level, but not inside a method. The way I see it, enums are almost like constants, so why not use them inside methods?

In my program, enum1 is allowed, but enum2 is not. Why?

enum enum1 {A, B, C};

public static void main(String[] args)
{
    enum enum2 {A, B, C};  // only on a top level class or interface
}
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Cindy Langdon
  • 611
  • 6
  • 12
  • See this thread http://stackoverflow.com/questions/11026626/why-java-doesnt-allow-to-define-enum-within-a-method – nicko Jun 17 '14 at 20:37
  • 1
    So, you are just pointing to another question which says that they don't know what is the reason.... – Cindy Langdon Jun 17 '14 at 20:56
  • 1
    @user2864740 But WHY? It is the same thing as saying that you can have any color, except BLUE. – Cindy Langdon Jun 17 '14 at 20:57
  • 1
    @user2864740 Not entirely true; classes *can* be defined inside methods. (Try it!). – Jesper Jun 17 '14 at 21:09
  • @Jesper Well, hmmpf. I was wrong, what a curious construct. – user2864740 Jun 17 '14 at 21:12
  • @user2864740 Yes, it's a little-known feature, and almost nobody uses it, but it's possible. – Jesper Jun 17 '14 at 21:13
  • **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

4 Answers4

8

Because enums are a special type of class definition.

This doc describes some information about special things the compiler does including adding static methods (valueOf). While you could declare an anonymous class withing the context of a method, it could not have static methods.

jmj
  • 237,923
  • 42
  • 401
  • 438
Brett Okken
  • 6,210
  • 1
  • 19
  • 25
3

It may have to do with the fact that Enums are compiled similarly to classes. For the same reason you cannot declare a class definition inside a method, you cannot declare in enum either.

Adam Yost
  • 3,616
  • 23
  • 36
1

Enums in Java are actually creating a class, which causes them to have limitations like this.

http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

John C
  • 500
  • 3
  • 8
0

Enumerations are way more than constant, you can create constructor for them. They are like Classes, you can't define a class in a method, it's the same for enumeration. If you want constant, you should better consider using final static var