函数式接口
概念:有且仅有一个抽象方法的接口;Java中的函数式编程体现就是Lambda,所以函数式接口就是可 以适用于Lambda使用的接口。
常见的函数接口:Runnable,Callable,Compapator,FileFilter
格式:确保接口有且仅有一个抽象方法:
修饰符 interface 接口名称{
public abstract 返回值类型 方法名称(可选参数信息)
}
@FunctionalInterface注解:
JDK1.8新特性。
作用:用来修饰接口,告诉编译器该接口是函数式接口,如果不是则会编译失败。
自定义函数式接口(无参无返回)
@FunctionalInterface
interface Eatable{
void eat();
}
public class DemoStu {
public static void main(String[] args) {
test(()-> System.out.println("此肉"));
}
public static void test(Eatable e){
e.eat();
}
}
自定义函数式接口(有参有返回)
@FunctionalInterface
interface Sumable{
int sum(int a,int b);
}
public class FunctionInterfaceDemo02 {
public static void main(String[] args) {
add(12,23,(a,b)->a+b);
}
public static void add(int a,int b,Sumable s){
System.out.println(s.sum(a,b));
}
}