java - @FunctionalInterfaces 可以有默认方法吗?

标签 java java-8

为什么我不能使用默认方法实现创建 @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/

相关文章:

java - 读入一个没有标点符号的文件

java - 使用 JDK8 Stream 如何迭代嵌套对象

java - 读取由 unicode 字符终止的文件

java - 如何避免 Hibernate 拦截器审核中出现 StackOverflowException

java - 将长整型数转换为字节数组

java - 跟踪字符串对

java - Java synchronized关键字与Spring @Transactional注解的逻辑对比

java - Request Param 的可选参数是一种不好的做法吗?

java - 如何使用 Java 8 Stream 从 Map 列表中的字符串获取列表?

java - 如何使用 Java8 流从带有键列表的 Map 中获取值