Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

can't create enum in inner class

 
ankur trapasiya
Ranch Hand
Posts: 160
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



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???
 
Ruediger Froehlich
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 160
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but we can create static final members in inner class so it should allow us to make enum in inner class...........
 
Ankit Garg
Sheriff
Posts: 9521
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
ankur trapasiya
Ranch Hand
Posts: 160
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
got it ... thanks ankit.....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic