Lambda exercise 3: There are parameters and return values (custom interface)

There are parameters and return values ​​(custom interface)

Lambda expressions have parameters and return values. Practice
Requirements:
Given a calculator Calculator interface, it contains an abstract method calc that can add two int numbers to get the sum value.
Use the standard format of lambda to call the invokeCalc method to complete the correlation between 120 and 145. Add calculation

Code

package demo06.Lambda;
/*
    定义一个计算器Calculator接口,内含抽象方法calc可以将两个int数字相加得到和值
*/
public interface Calculator {
    
    
    //定义一个计算两个int整数和的方法并返回结果
    public abstract int calc(int a,int b);
}
package demo06.Lambda;

/*
    lambda表达式有参数有返回值练习
    需求:
        给定一个计算器Calculator接口,内含抽象方法calc可以将两个int数字相加得到和值
        使用lambda的标准格式调用invokeCalc方法,完成120与145的相加计算
*/
public class Demo01Calculator {
    
    
    public static void main(String[] args) {
    
    
        //调用invokkeCalc方法,方法的参数是一个接口,可以使用匿名内部类
        invokeCalc(10, 20, new Calculator() {
    
    
            @Override
            public int calc(int a, int b) {
    
    
                return a + b;
            }
        });

        //使用lambda表达式简化匿名内部类的书写
        invokeCalc(120,145,(int a,int b)->{
    
    
            return a + b;
        });

    }

Code demo:

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_44664432/article/details/108440581