Monday, September 28, 2009

What can be done with enums?

This post shows the various things that enums can do. Enum data type was introduced since Java 5 and is a very powerful type. It is a special type of class which contains constant objects, instance variables,constructors,overloaded constructors, methods and overloaded methods as well. Enums can be declared outside or inside the class.Another important feature of enums is semicolon is optional.


 Following is an example of enum outside the class.

enum ConeSize {
SMALL(8,"Small"),BIG(10,"Big"),LARGE(15,"Large"){
  public String getType(){ return "Premiurm";} // overloaded method for LARGE
};
/* instance variables. Remember enum is a special type of class so it can have variables and constructors and methods*/
private String name;
private int size;
//enum constructor
ConeSize (int size,String name){
  this.size= size;
  this.name = name; 
}
// methods
public int getSize(){
  return size;
}
public String getName(){
  return name;
}
public String getType(){
  return "Simple";
}
}

public class MyClass{
  public static void main(String args[]){
     ConeSize s = ConeSize.BIG;
     ConeSize s1=ConeSize.LARGE;
     System.out.println(s.getName()+" "+s.getSize()+" "+s.getType());
     System.out.println(s1.getName()+" "+s1.getSize()+" "s1.getType());
}

when the above code is compiled and run then we get the following output:
Big 10 Simple
Large 15 Premium

When the getType() method is invoked on s1 then the overloaded version of getType is run while for Big and Small conesize the normal version of getType runs.

If your enum is inside the class, the method for invoking an enum will be different.
for example:
public class Cone {
ConeSize {BIG,SMALL,LARGE}
ConeSize size;
}
public class MyClass{
 public static void main(String args[])
{
    Cone cone = new Cone();
    cone.size = Cone.ConeSize.BIG; // the enclosing class name is required.
}