Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

enum within a method?  RSS feed

 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I was wondering why we cannot declare an enum within a method when a class can be declared in a method?

Can anybody advise?

Thanks,
Prashant
 
Rancher
Posts: 42975
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Only anonymous classes can be declared inside of methods. How would you use an anonymous enum?
 
Ranch Hand
Posts: 120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Ulf Dittmer wrote:Only anonymous classes can be declared inside of methods.





It compiles and runs fine.
 
Sheriff
Posts: 5878
832
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Both anonymous and local inner classes can be defined inside a method, as Moojid demonstrated in his example.

In Java literature, we can say that enums are implicitly static. Because we can use it as Apple.bigApple, where Apple is an enum type. You know that static declarations (declarations of static variables/static classes) are not valid inside a method. Therefore we couldn't declare enums inside a method local. But this is a *one* reason only. There are some other technical reasons rely on that.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!