@FunctionalInterface是JDK 8 中新增的注解类型,用来描述一个接口是函数式接口。例如我们熟悉的Runnable 接口:
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
函数式接口的特征:
-
接口中只定义了一个抽象方法。如
TestInterface接口中,只有一个sayHello()方法。@FunctionalInterface public interface TestInterface { public abstract void sayHello(); } -
接口中允许存在重写
Object类的抽象方法。如在TestInterface接口中,新增一个toString()方法,仍然不会报错。因为TestInterface接口的实现类一定是Object类的子类,继承了toString()方法,也就自然实现了TestInterface接口定义的抽象方法toString()。@FunctionalInterface public interface TestInterface { public abstract void sayHello(); public abstract void toString(); } 函数式接口可以使用
Lambda表达式、方法引用、构造函数引用来创建。其中的Lambda表达式在下一篇文章中会说明。
使用
@FunctionalInterface可以防止以后在接口中添加新的抽象方法签名。