在Java中,枚举类型可以实现接口吗?

在Java中,枚举类型可以实现接口吗?

是的,Enum在 Java 中实现了一个接口,当我们需要实现一些与给定对象或类的可区分属性紧密耦合的业务逻辑时,它会很有用。 枚举Java 1.5版本中添加的一种特殊数据类型。枚举是常量,默认情况下它们是静态的 strong>和final,因此枚举类型字段的名称采用大写字母

示例

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

输出

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

以上就是在Java中,枚举类型可以实现接口吗?的详细内容,更多请关注其它相关文章!