This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes enum within a method? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "enum within a method?" Watch "enum within a method?" New topic
Author

enum within a method?

Prash Negu
Ranch Hand

Joined: Apr 20, 2009
Posts: 45
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
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41181
    
  45
Only anonymous classes can be declared inside of methods. How would you use an anonymous enum?


Ping & DNS - my free Android networking tools app
Moojid Hamid
Ranch Hand

Joined: Mar 07, 2009
Posts: 120
Ulf Dittmer wrote:Only anonymous classes can be declared inside of methods.




It compiles and runs fine.
Devaka Cooray
ExamLab Creator
Saloon Keeper

Joined: Jul 29, 2008
Posts: 3029
    
  35

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.


Author of ExamLab ExamLab - a free SCJP / OCPJP exam simulator
What would SCJP exam questions look like? -- Home -- Twitter -- How to Ask a Question
 
jQuery in Action, 2nd edition
 
subject: enum within a method?
 
Similar Threads
enum within a class
String support for switch case statement
enums
enumerations
Doubt About Enum in java 1,5