Friday 2 May 2014

Declaring method in enum


enum MonthEx{
 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;
 
 MonthEx(int num, String msg){
  this.num = num;
  this.msg = msg;
 }
 
 void getInfo(){
  System.out.println(num +" "+ this +" "+ msg);
 }
 
 public static void main(String args[]){
  for(MonthEx m : MonthEx.values()){
   m.getInfo();
  }
 }
}

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 an enum. For example, they 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 an 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