Declaring Constructors, Methods, and Variables in an enum : enum « Object Oriented « SCJP






enum Problem {
    // 8, 10 & 16 are passed to the constructor
    BIG(8), HUGE(10), SMALL(16);
    Problem(int ounces) { // constructor
      this.ounces = ounces;
    }

    private int ounces;      
    public int getOunces() {
      return ounces;
    }
}

class MyClass {
   Problem size;    

   public static void main(String[] args) {
      MyClass drink1 = new MyClass();
      drink1.size = Problem.BIG;

      MyClass drink2 = new MyClass();
      drink2.size = Problem.SMALL;

      System.out.println(drink1.size.getOunces());
      for(Problem cs: Problem.values())
         System.out.println(cs + " " + cs.getOunces());
   }
}








6.11.enum
6.11.1.Java enum
6.11.2.Declaring Enums
6.11.3.An example of declaring an enum inside a class
6.11.4.You cannot declare enums in a method
6.11.5.It is optional to put a semicolon at the end of the enum declaration
6.11.6.Declaring Constructors, Methods, and Variables in an enum
6.11.7.Enums are subclasses of java.lang.Enum.
6.11.8.You can declare an enum anywhere you can declare a class.
6.11.9.Enums inherit data and methods from Object.
6.11.10.Enums may be converted and cast according to the same rules that govern any class that extends Object.
6.11.11.Enums may have main() methods and can be invoked as applications.
6.11.12.Enums that have no explicit constructors get default no-args constructors.
6.11.13.Enums have built-in name() and toString() methods, both of which return the name of the current instance.
6.11.14.You can add data, methods, and constructors to an enum.