在Java中使用@FunctionalInterface注解标记函数式接口是否强制性的?
仅定义了一个抽象方法的接口称为函数式接口。没有必要使用@FunctionalInterface注解标记函数式接口,编译器不会抛出任何错误。但建议使用@FunctionalInterface注解,以避免意外添加额外的抽象方法。如果一个使用@FunctionalInterface注解标记的接口有超过一个抽象方法,那么会抛出一个编译期错误。
语法
@FunctionalInterface
interface interface_name {
// only one abstarct method declaration
}示例
@FunctionalInterface
interface Shape {
void printArea(int x);
}
public class SquareTest {
public static void main (String args[]) {
Shape square = (x) -> { // Lambda Expression
System.out.println("The area of a square is: "+ x*x);
};
square.printArea(7);
}
}输出
The area of a square is: 49
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP