Home > Java > javaTutorial > body text

In Java, can enumeration types implement interfaces?

WBOY
Release: 2023-09-08 14:17:04
forward
860 people have browsed it

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());
   }
}
Copy after login

Output

<strong>Addition: 30
Subtraction: 10</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template