Java枚举enum可以有抽象方法! -Recepİnanç


在这篇文章中,我想与大家分享我今天学习到的有关Java中的Enums的一项很棒的功能。也就是说,枚举可以具有抽象方法,并且每个成员都需要实现它。
以下代码显示了如何声明和实现枚举的抽象方法-就像其他任何类一样:)

enum Calculator
{
    ADD("+") { int calculate(int a, int b) { return a + b; }},
    SUBTRACT(
"-") { int calculate(int a, int b) { return a - b; }},
    MULTIPLY(
"*") { int calculate(int a, int b) { return a * b; }},
    DIVIDE(
"/") { int calculate(int a, int b) { return a / b; }};

    Calculator(String sign)
    {
        this.sign = sign;
    }

    private String sign;

    abstract int calculate(int a, int b);
// this is how you declare 

    public String getSign()
    {
        return sign;
    }
}

我创建了以下代码片段,以向您展示此功能的示例应用:

public static void main(String[] args)
{
    calculatorTest(4, 2, Calculator.ADD);
    calculatorTest(4, 2, Calculator.SUBTRACT);
    calculatorTest(4, 2, Calculator.MULTIPLY);
    calculatorTest(4, 2, Calculator.DIVIDE);
}

static void calculatorTest(int a, int b, Calculator operation) {
    System.out.println(a + " " + operation.getSign() + " " + b + " = " + operation.calculate(a, b));
}