[英]Implement `IntegerMath addition` and `IntegerMath subtraction` without using lambda?
I'm currently learning the concept of Lambda in java and I have encountered the following code.我目前正在学习java中Lambda的概念,我遇到了以下代码。 The IntegerMath addition
and IntegerMath subtraction
were defined using lambda. IntegerMath addition
和IntegerMath subtraction
是使用 lambda 定义的。 However, I was just curious how to implement IntegerMath addition
and IntegerMath subtraction
without using lambda?但是,我只是好奇如何在不使用 lambda 的情况下实现IntegerMath addition
和IntegerMath subtraction
? It would be great if the suggestion can be accompanied by some code!如果建议可以附上一些代码,那就太好了! Thanks in advance for any help!在此先感谢您的帮助!
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));
}
}
Your lambdas are functionally equivalent to anonymous classes like,你的 lambdas 在功能上等同于匿名类,比如,
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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.