Home  >  Article  >  Java  >  In Java, can enumeration types implement interfaces?

In Java, can enumeration types implement interfaces?

WBOY
WBOYforward
2023-09-08 14:17:04861browse

In Java, can enumeration types implement interfaces?

Yes, Enum implements an interface in Java, when we need to implement some business logic that is tightly coupled with the distinguishable properties of a given object or class , it can be useful. Enumeration is a special data type added in Java 1.5 version. Enumerations are constants , by default they are static strong> and final, so the names of enum type fields are capitalized letter.

Example

interface EnumInterface {
   int calculate(int first, int second);
}
enum EnumClassOperator implements <strong>EnumInterface </strong>{ // <strong>An Enum implements an interface</strong>
   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);
   }
}
<strong>// Main Class</strong>
public class EnumTest {
   public static void main (String [] args) {
      Operation add = new Operation(20, 10, <strong>EnumClassOperator.ADD</strong>);
      Operation subtract = new Operation(20, 10, <strong>EnumClassOperator.SUBTRACT</strong>);
      System.out.println("Addition: " + add.calculate());
      System.out.println("Subtraction: " + subtract.calculate());
   }
}

Output

<strong>Addition: 30
Subtraction: 10</strong>

The above is the detailed content of In Java, can enumeration types implement interfaces?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete