Friday 2 May 2014

Declaring fields inside enum type

enum types in Java are much powerful and you can declare fields in addition to constants.

enum Month{
 JANUARY(1, "31 Days"),
 FEBRUARY(2, "28 or 29 Days"),
 MARCH(3, "31 Days"),
 APRIL(4, "30 days"),
 MAY(5, "31 Days"),
 JUNE(6, "30 Days"),
 JULY(7, "31 Days"),
 AUGUST(8, "31 Days"),
 SEPTEMBER(9, "30 Days"),
 OCTOBER(10, "31 Days"),
 NOVEMBER(11, "30 Days"),
 DECEMBER(12, "31 Days");
 
 int num;
 String msg;
 
 Month(int num, String msg){
  this.num = num;
  this.msg = msg;
 }
 
 public static void main(String args[]){
  for(Month m : Month.values()){
      System.out.println(m.num +" "+ m +" "+ m.msg);
  }
 }
}

Output
1 JANUARY 31 Days
2 FEBRUARY 28 or 29 Days
3 MARCH 31 Days
4 APRIL 30 days
5 MAY 31 Days
6 JUNE 30 Days
7 JULY 31 Days
8 AUGUST 31 Days
9 SEPTEMBER 30 Days
10 OCTOBER 31 Days
11 NOVEMBER 30 Days
12 DECEMBER 31 Days

Compiler automatically adds some special methods when it creates enum. For example, enum have a static values method that returns an array containing all of the values of the enum in the order they are declared.

Note: constructor for enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor directly. 

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment