为什么我不能使用默认方法实现创建 @FunctionalInterface
?
@FunctionalInterface
public interface MyInterface {
default boolean authorize(String value) {
return true;
}
}
最佳答案
您可以在 functional interface 中使用默认方法但它的契约(Contract)要求您提供一个单一的抽象方法(或 SAM)。由于默认方法有一个实现,所以它不是抽象的。
Conceptually, a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract.
和
If a type is annotated with this annotation type, compilers are required to generate an error message unless:
The type is an interface type and not an annotation type, enum, or class.
The annotated type satisfies the requirements of a functional interface.
这里不满足函数式接口(interface)的要求,需要提供一个抽象方法。例如:
@FunctionalInterface
interface MyInterface {
boolean authorize(int val);
default boolean authorize(String value) {
return true;
}
}
请注意,如果您声明的抽象方法覆盖了 Object 类中的公共(public)方法之一,则该方法不计算在内,因为此接口(interface)的任何实现都将至少通过 Object 的类实现这些方法。例如:
@FunctionalInterface
interface MyInterface {
default boolean authorize(String value) {
return true;
}
boolean equals(Object o);
}
不编译。
关于java - @FunctionalInterfaces 可以有默认方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30165060/