Thursday, November 14, 2013

Enums





What is Enum ?

This is not only an hereditary thing for Java. Most of the languages(C, C#, C++, Ada, Pascal...) use "enums".

  • This is a special data type which is called enum type not a int, long String or other type.
  • The things in the enumerated list are called enums.
  • This was introduced to Java in Java 5.0
  • Enum is related to java.lang.Enum and it is an abstract class.
  • Enums are comparable and serializable.
What the hell of using this enum ?

  • Very simply we can say, enum is used to represent fixed number of well known values.
How to declare enums ?

  • Enum declaration is like class declaration. Look at that,
              enum Fruits { Apple, Mango, Pineapple, Cherry };

  • Enums can be declared as their own class inside another class or outside another class. But when it is outside the class, it cannot be used static, final, abstract,protected or private keywords.
  • Enums can not be declared within a method.
  • In the example I have used semi colon at the end. But it is optional thing, If you want you can use otherwise you can leave it without semi colon.

Rules for enums

  • Enum types cannot be extended. They are final types(Final subclass of java.lang.Enum).
  • Enum can contain constructors, methods, variables and constant class bodies.
  • Enum constructors can have arguments and they can be overloaded.
  • Enum constants are implicitly public static and final, cannot be changed once created.

Enum outside  the class






Enum inside the class






Enum with constructors

                     enum Apple { RED ("eat"), GREEN ("cook") }

  • Think about above declaration of enum.
  • Enums can have constructors to pass data while creating enum constants.
                     Ex: RED is associated with 'eat'

  • It cannot be invoked an enum constructor directly. It is invoked automatically with the arguments you define after the constant value.
                      Ex: GREEN ("cook")

  • Enum constructors can be overloaded.
  • There can be more than one arguments.
  • Constructors for enum type should be declared as private. 
Following code is an example for enums with constructors.


enum Apple {
   RED("drink"), GREEN("cook");  
   
   private final String color;      
   
   Apple(String color) {     
      this.color = color;
   }
   
   String getColor() {      
      return color;
   }
}
 
public class EnumTest3 {
 
   public static void main(String[] args) {
    
      for (Apple a : Apple.values()) {
         System.out.println(a +" Apples are used to "+ a.getColor());
      }
   }
}