File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "enum within a method?" Watch "enum within a method?" New topic

enum within a method?

Prash Negu
Ranch Hand

Joined: Apr 20, 2009
Posts: 46

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

Can anybody advise?

Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
Only anonymous classes can be declared inside of methods. How would you use an anonymous enum?
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

Joined: Jul 29, 2008
Posts: 3925

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
I agree. Here's the link:
subject: enum within a method?
It's not a secret anymore!