Can Enum implements an interface in Java?

JavaObject Oriented ProgrammingProgramming

Yes, Enum implements an interface in Java, it can be useful when we need to implement some business logic that is tightly coupled with a discriminatory property of a given object or class. An Enum is a special datatype which is added in Java 1.5 version. The Enums are constants, by default they are static and final so the names of an enum type fields are in uppercase letters.

Example

interface EnumInterface {
   int calculate(int first, int second);
}
enum EnumClassOperator implements EnumInterface { // An Enum implements an interface
   ADD {
      @Override
      public int calculate(int first, int second) {
         return first + second;
      }
   },
   SUBTRACT {
      @Override
      public int calculate(int first, int second) {
         return first - second;
      }
   };
}
class Operation {
   private int first, second;
   private EnumClassOperator operator;
   public Operation(int first, int second, EnumClassOperator operator) {
      this.first = first;
      this.second = second;
      this.operator = operator;
   }
   public int calculate() {
      return operator.calculate(first, second);
   }
}
// Main Class
public class EnumTest {
   public static void main (String [] args) {
      Operation add = new Operation(20, 10, EnumClassOperator.ADD);
      Operation subtract = new Operation(20, 10, EnumClassOperator.SUBTRACT);
      System.out.println("Addition: " + add.calculate());
      System.out.println("Subtraction: " + subtract.calculate());
   }
}

Output

Addition: 30
Subtraction: 10
raja
Published on 01-Aug-2019 11:01:00
Advertisements