是的,Enum在 Java 中实现了一个接口,当我们需要实现一些与给定对象或类的可区分属性紧密耦合的业务逻辑时,它会很有用。 枚举是Java 1.5版本中添加的一种特殊数据类型。枚举是常量,默认情况下它们是静态的 strong>和final,因此枚举类型字段的名称采用大写字母。
示例
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
登录后复制
以上就是在Java中,枚举类型可以实现接口吗?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!