函数式接口是 java 8 中的新增功能,它只允许在其内部有一个抽象方法
。
这些接口也称为单一抽象方法接口(SAM 接口 - Single Abstract Method interfaces)。
在 Java 8 中,函数式接口也可以使用 lambda 表达式、方法引用和构造函数引用来表示。
Java 8 也引入了一个注解,例如:@FunctionalInterface,当你注解的接口违反了一个抽象方法的约定时,它可以用于编译器级别的错误。
让我们构建第一个函数式接口:
@FunctionalInterface public interface MyFirstFunctionalInterface { public void firstWork(); }
让我们尝试添加另一个抽象方法:
@FunctionalInterface public interface MyFirstFunctionalInterface { public void firstWork(); public void doSomeMoreWork(); //error }
以上将导致编译器错误,如下所示:
Unexpected @FunctionalInterface annotation @FunctionalInterface ^ MyFirstFunctionalInterface is not a functional interface multiple non-overriding abstract methods found in interface MyFirstFunctionalInterface
日期:2020-09-17 00:09:46 来源:oir作者:oir