Monday, January 23, 2012

Java enum - constant-specific method implementations

This is a one of the interesting feature with java enum introduced with java 1.5. Normally We are using java enum to define some set of constants which enhance code readability and provides compile time type safety and more. If We want to define some behaviors specific to each of the constants define in enum, How Can We do it? 

There is a way to associate a different behavior with each enum constant.Declare an abstract method in the enum type, and override it with a concrete method for each constant in a constant-specific class body. Here is an example.

/**
 * @author semikas
 *
 */
public enum Operation {

 PLUS {
      @Override
      double apply(double x, double y) {
          return x + y;
      }
 },
 MINUS {
       @Override
       double apply(double x, double y) {
           return x - y;
       }
 },
 TIMES {
      @Override
      double apply(double x, double y) {
           return x*y;
      }
 },
 DIVIDE {
       @Override
       double apply(double x, double y) {
           return x/y;
       }
 };

 abstract double apply(double x, double y);
}

2 comments:

  1. Very Good example man, simple and clear. I agree with you Enum is very versatile and one of the great addition in Java. I have also shared some of less know examples of enum in java , let me know how do you find it.

    ReplyDelete
  2. Read "Effective Java" book which discuss the advance aspects of JAVA and the best practices.

    ReplyDelete

Share

Widgets