Can Enum implements an interface in Java?



Yes, an Enum implements an Interface in Java. It can be useful when we need to implement business logic that is tightly coupled with a specific property of a given object or class.

Before implementing the interface with an enum, let's discuss enums and interfaces in Java with a code snippet for better understanding.

Enum in Java

In Java, an Enum (i.e., an enumeration) is a special data type added in Java version 1.5. Enums are constants by default; the names of an enum type's fields are in uppercase letters.

In the Java programming language, you can define an Enum type by using the enum keyword. For example, you would specify a day of the week enum type as follows:

public enum Days {
   SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
   THURSDAY, FRIDAY, SATURDAY 
}

Interface in Java

In Java, an Interface is not a class but a special type used to group abstract methods (and optionally static or default methods with empty bodies). An interface cannot be instantiated directly, but it can be implemented by any class using the implements keyword.

The following is a simple "Calc" interface that contains different methods:

interface Calc {
   int add(int a, int b);
   int sub(int a, int b);
}  

Example

In this example, we demonstrate how an enum in Java can implement an interface to perform different operations, such as "addition" and "subtraction" -

//Defining an Interface
interface EnumInterface {
   int calculate(int first, int second);
}

// An Enum implements an interface
enum EnumClassOperator implements EnumInterface { 
   ADD {
      @Override
      public int calculate(int first, int second) {
         return first + second;
      }
   },
   SUBTRACT {
      @Override
      public int calculate(int first, int second) {
         return first - second;
      }
   };
}

//Operation class
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

The above program produces the following output -

Addition: 30
Subtraction: 10
Updated on: 2025-05-29T17:58:20+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements