Pages

Wednesday 27 November 2013

Enumerations in Java are class types



       An enumeration in Java is a class type. It can have constructors, instance variables of enumeration can be declared, you can define methods in an enumeration, one enumeration can inherit the other and it can also implement interfaces. 

Points to remember when using Enumerations

1.      You can’t instantiate an enum using new.

2.      Every enumeration constant is an object of its enumeration type.

3.      You can define a constructor for an enum, this constructor is called only after each enumeration constants are created.

Important two methods of enumerations

1.      The values () method: It returns the list of enumeration constants in the form of an array.
        
            The general form of method is as shown below.


            public static enum-typeName[] values()

                 
    



2.      The valuesOf () method: It returns the enumeration constant whose value corresponds to the string passed to the method. 

                          The general form of method is as shown below.
                                      

       public static enum-typeName  valuesOf(String str)






        Consider the below program example that shows enumeration is a class type and also illustrates the use of the above mentioned two methods.

package blog.enumeration;

public enum StudentNames
{
  Rama(21),Shama(18),Ravi(20);
 
  private int age;
 
  StudentNames(int age)
  {
                  this.age=age;
  }
 
  int ageOfStudent()
  {
                  return age;
  }
}



package blog.enumeration;

public class StudentNameEnumDemo
{
  public static void main(String[] args)
  {
                StudentNames name;
               
                // display the name and age of particular student.
                   name=StudentNames.valueOf("Ravi");
                  
                   int age=StudentNames.Ravi.ageOfStudent();
                  
                   System.out.println(name+"'s age is "+age);
                   System.out.println();
                  
                // display the list of names in Enum and their ages.
                   for(StudentNames names:StudentNames.values())
                   System.out.println(names+"'s age is "+names.ageOfStudent());
                 
  }
}


Output:

Ravi's age is 20

Rama's age is 21
Shama's age is 18
Ravi's age is 20