This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Soft Skills and have John Sonmez on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes can't create enum in inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "can Watch "can New topic
Author

can't create enum in inner class

ankur trapasiya
Ranch Hand

Joined: Sep 24, 2010
Posts: 160




when i compile this code i get error something like "enum declaration allowed only in static context"...

what does it mean ??? can't we create enums in inner class???


OCPJP(83%)
Ruediger Froehlich
Greenhorn

Joined: Nov 18, 2010
Posts: 2
This is from the SCJP study guide:

So what gets created when you make an enum? The most important thing to
remember is that enums are not Strings or ints! Each of the enumerated CoffeeSize
types are actually instances of CoffeeSize. In other words, BIG is of type CoffeeSize.
Think of an enum as a kind of class, that looks something (but not exactly) like this:
// conceptual example of how you can think
// about enums
class CoffeeSize {
public static final CoffeeSize BIG =
new CoffeeSize("BIG", 0);
public static final CoffeeSize HUGE =
new CoffeeSize("HUGE", 1);
public static final CoffeeSize OVERWHELMING =
new CoffeeSize("OVERWHELMING", 2);
public CoffeeSize(String enumName, int index) {
// stuff here
}
public static void main(String[] args) {
System.out.println(CoffeeSize.BIG);
}
}
Notice how each of the enumerated values, BIG, HUGE, and OVERWHELMING,
are instances of type CoffeeSize. They're represented as static and final, which in
the Java world, is thought of as a constant.


So, since Enum-Values can be thought of as static final Values you have to declare your Inner class as static, too or move the Enum to the Outer Class.
Static Declarations can only be made in a static or top-level Class.
ankur trapasiya
Ranch Hand

Joined: Sep 24, 2010
Posts: 160

but we can create static final members in inner class so it should allow us to make enum in inner class...........
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9319
    
  17

but we can create static final members in inner class so it should allow us to make enum in inner class.

You can only create static final members in inner classes of type String and primitives i.e. compile time constants not any type you like...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
ankur trapasiya
Ranch Hand

Joined: Sep 24, 2010
Posts: 160

got it ... thanks ankit.....
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: can't create enum in inner class