面试题答案
一键面试1. 函数式接口定义:
在Java中,函数式接口是指只包含一个抽象方法的接口。Java 8引入了函数式接口,以便可以使用Lambda表达式来实现该接口的抽象方法。函数式接口通常用于支持函数式编程风格。为了确保一个接口是函数式接口,可以使用@FunctionalInterface
注解,虽然不是必须的,但使用该注解有助于在编译时发现不符合函数式接口定义的错误。
2. 自定义函数式接口及Lambda实现示例:
// 自定义函数式接口
@FunctionalInterface
interface MyFunctionalInterface {
int performOperation(int a, int b);
}
public class FunctionalInterfaceExample {
public static void main(String[] args) {
// 使用Lambda表达式实现函数式接口
MyFunctionalInterface addition = (a, b) -> a + b;
MyFunctionalInterface multiplication = (a, b) -> a * b;
int result1 = addition.performOperation(3, 5);
int result2 = multiplication.performOperation(4, 6);
System.out.println("Addition result: " + result1);
System.out.println("Multiplication result: " + result2);
}
}
在上述代码中,MyFunctionalInterface
是一个自定义的函数式接口,它只有一个抽象方法performOperation
。在main
方法中,使用Lambda表达式创建了MyFunctionalInterface
接口的实例,分别实现了加法和乘法的功能。