枚举可以在 Java 中实现接口吗?
是的,在 Java 中,枚举可实现一个接口,当需要实现一些与特定对象或类的区别属性紧密结合的业务逻辑时,此功能非常有用。枚举是一种特殊的数据类型,它被添加到 Java 1.5 版本中。枚举是常量,默认情况下它们是静态且最终的,因此枚举类型字段的名称使用大写字母来表示。
示例
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()); } }
输出
Addition: 30 Subtraction: 10
广告