Sunday, November 20, 2011

Enum as nested class

Tip: Enums can be declared as a top level class, or an inner class, but not within a method.

We can easily test this by defining a class with Enum defined within a method:
class LocalEnum {
 void printCar () {
  enum CarClass { // compilation error here
   COMPACT, MIDSIZE, FULLSIZE;
  }
  System.out.println(CarClass.COMPACT);
  }
}
If you try to compile and run above code snippet you will get error in line enum CarClass.

On the other hand if we take out enum CarClass out of method the definition will be fine.
class LocalEnum {
 enum CarClass {
  COMPACT, MIDSIZE, FULLSIZE;
 }

 static void printCar() {
  System.out.println(CarClass.COMPACT);
 }

 public static void main(String[] args) {
  printCar();
 }
}
We have modified the little bit above so that it could be run easily by putting a main method, printCar is static and enum is defined out of the method. It works ....

Available in Android Market

No comments:

Post a Comment