@FunctionalInterfaces可以有默认方法吗? [英] Can @FunctionalInterfaces have default methods?

查看:379
本文介绍了@FunctionalInterfaces可以有默认方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使用默认方法实现创建 @FunctionalInterface

Why can't I create a @FunctionalInterface with a default method implementation?

@FunctionalInterface
public MyInterface {
    default boolean authorize(String value) {
        return true;
    }
}


推荐答案

你可以在功能界面中使用默认方法,但其合同要求您提供一种抽象方法(或SAM)。由于默认方法具有实现,因此它不是抽象的。

You can have default methods in a functional interface but its contract requires you to provide one single abstract method (or SAM). Since a default method have an implementation, it's not abstract.


从概念上讲,功能接口只有一个抽象方法。
由于默认方法有实现,因此它们不是抽象的。

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.

这里您不满足功能接口的要求,因此您需要提供一种抽象方法。例如:

Here you don't satisfy the functional interface's requirement, so you need to provide one abstract method. For example:

@FunctionalInterface
interface MyInterface {

    boolean authorize(int val);

    default boolean authorize(String value) {
        return true;
    }
}

请注意,如果您声明一个覆盖其中一个的抽象方法一个来自Object类的公共方法,它不计算,因为这个接口的任何实现都将至少通过Object的类来实现这些方法。例如:

Note that if you declare an abstract method overriding one of a public method from the Object's class it doesn't count, because any implementation of this interface will have an implementation of those methods through at least the Object's class. For example:

@FunctionalInterface
interface MyInterface {

    default boolean authorize(String value) {
        return true;
    }

    boolean equals(Object o);
}

无法编译。

这篇关于@FunctionalInterfaces可以有默认方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆