函数式接口FunctionalInterface

JDK8新增的函数式编程

FunctionalInterface跟Interface相似,但是只能有一个抽象方法,可以有多个默认的实现,不能有其他已实现的方法。

1.使用@FunctionalInterface注解

2.必须要有一个抽象方法,且只能有一个抽象方法,不能有非抽象方法

3.可以有多个特定的实现。

4.定义属性只能是public static 或 public final类型

 

 1 /*
 2  * TestFunction.java
 3  */
 4 @FunctionalInterface
 5 interface TestFunction {
 6     //加法的实现
 7     TestFunction ADD = (a,b) -> {
 8         return a+b;
 9     };
10     
11     //减法的实现
12     TestFunction SUB = (a,b) -> {
13         return a-b;
14     };
15     
16     //抽象的方法
17     public int call(int a, int b) ;
18 }

 

 1 /*
 2  * Demo.java
 3  */
 4 public class Demo 
 5 {
 6     public static void main( String[] args )
 7     {
 8         int a=4,b=2;
 9         
10         //使用函数接口的ADD实现
11         int first = foo(a,b,TestFunction.ADD);
12         
13         //声明一个TestFunction,并使用lambda表达式实现函数接口,实现乘法
14         TestFunction fun = (int i,int j) -> {
15             return i*j;
16         };
17         
18         //使用函数接口的SUB实现
19         int second = foo(a,b,TestFunction.SUB);
20         
21         //使用声明的fun实现
22         int third = foo(a,b,fun);
23         
24         //使用Demo类的div方法
25         int four = foo(a,b,Demo::div);
26         
27         System.out.println("add:" + first + "\nsub:" + second + "\nmul:" + third + "\ndiv:" + four);
28         
29     }
30     
31     public static int foo(int a,int b, TestFunction fun) {
32         return fun.call(a, b);
33     }
34     
35     public static int div(int a, int b) {
36         return a/b;
37     }
38 }
输出结果
add:6
sub:2
mul:8
div:2

 

posted on 2021-06-09 09:49  pcant  阅读(166)  评论(0编辑  收藏  举报