不使用lambda实现`IntegerMath addition`和`IntegerMath减法`?

时间:2016-03-24 04:25:18

标签: java lambda interface

我目前正在学习Java中的Lambda概念,我遇到了以下代码。 IntegerMath additionIntegerMath subtraction是使用lambda定义的。但是,我只是好奇如何在不使用lambda的情况下实现IntegerMath additionIntegerMath subtraction?如果建议可以附带一些代码,那将是很棒的!在此先感谢您的帮助!

public class Calculator {

    interface IntegerMath {
        int operation(int a, int b);   
    }

    public int operateBinary(int a, int b, IntegerMath op) {
        return op.operation(a, b);
    }

    public static void main(String... args) {

        Calculator myApp = new Calculator();
        IntegerMath addition = (a, b) -> a + b;
        IntegerMath subtraction = (a, b) -> a - b;
        System.out.println("40 + 2 = " +
            myApp.operateBinary(40, 2, addition));
        System.out.println("20 - 10 = " +
            myApp.operateBinary(20, 10, subtraction));    
    }
}

1 个答案:

答案 0 :(得分:0)

你的lambda 功能等同于anonymous classes

IntegerMath addition = new IntegerMath() {
    @Override
    public int operation(int a, int b) {
        return a + b;
    }
};
IntegerMath subtraction = new IntegerMath() {
    @Override
    public int operation(int a, int b) {
        return a - b;
    }
};