Java接口作为方法入参
1/**
2 * 函数式接口和Lambda表达式<br>
3 * 1. 函数式接口:接口可以用作函数 --> 函数作为方法形参
4 * <p>
5 * 2. Lambda表达式简化了函数式接口的使用
6 *
7 * @author wangy
8 * @version 1.0
9 * @date 2024/7/9 / 18:00
10 */
11
12interface MFunction<R, T> {
13 R apply(T t);
14}
15
16public class Gfunction {
17
18 /* 函数式接口作为形参 */
19 static <R, T> R applyFunc(MFunction<R, T> f, T n) {
20 return f.apply(n);
21 }
22
23 public static void main(String[] args) {
24 /* 传统方式 */
25 System.out.println(applyFunc(new MFunction<Integer, Integer>() {
26 @Override
27 public Integer apply(Integer t) {
28 return t * t;
29 }
30 }, 3));
31
32 /* 使用lambda表达式 */
33 System.out.println((Integer) applyFunc(x -> x * x, 5));
34 }
35}
36
37/// :~
38// 9
39// 25