函数接口是一个只有一个抽象方法的简单接口。lambda表达式可以通过java8中的函数接口使用。我们可以通过在接口中定义单个抽象方法(SAM)来声明我们自己的/自定义的函数接口。
interface CustomInterface {
//抽象方法
}@FunctionalInterface
interface CustomFunctionalInterface {
void display();
}
public class FunctionInterfaceLambdaTest {
public static void main(String args[]) {
//使用匿名内部类
CustomFunctionalInterface test1 = new CustomFunctionalInterface() {
public void display() {
System.out.println("使用匿名内部类显示");
}
};
test1.display();
//使用Lambda表达式
CustomFunctionalInterface test2 = () -> { // lambda 表达式
System.out.println("使用Lambda表达式显示");
};
test2.display();
}
}输出结果
使用匿名内部类显示 使用Lambda表达式显示