功能接口

Funtional Interface

我是函数式界面的新手,今天我正在从几个教程站点学习。我有一个问题请提供您的建议并指导我。

下面提到的代码有问题要问我。

@FunctionalInterface
interface Demo {
    Object clone();   // protected
    //int hashCode();              // public
    //boolean equals(Object c); // public
    //public void wait(); // final so we cannot override this one.
}

对象 class 是所有 java class 对象的父对象。 这里的 wait() 方法说没有被覆盖,因为这是最终的。所以这意味着 Demo 接口也是 Object class 的子对象(一般而言)。

> @FunctionalInterface means interface with exact one method declaration.

问题:那么,现在当 Object clone(); 方法未被注释时,代码可以正常工作。所以意味着这个方法是在接口Demo中声明的。但是当我们点击它的实现时,我们继续对象 class 的 clone() 方法。

当我们注释clone() 方法和取消注释equals() 方法时,我们会得到编译时错误,接口不是FunctionalInterface。为什么 ??????以及为什么它的功能接口与 clone() 方法。

请不要说clone()受保护,clone在Object class中受保护有什么关系。请帮我解释一下。

谢谢, sawai

由于 public boolean equals(Object c) 已经存在于 Object 中,Demo 没有声明任何新方法。要成为 FunctionalInterface,它应该只声明一个方法。

当您改为声明 public Object clone() 时,它是一种新方法,因为 Object 中的原始方法是 protected。因此可以认为是FunctionalInterface.

因为 clone() 被保护了。我知道你让我不要这么说,但我还是要说,因为这是答案。

http://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.8具体说:

For an interface I, let M be the set of abstract methods that are members of I that do not have the same signature as any public instance method of the class Object. Then, I is a functional interface if there exists a method m in M for which both of the following are true:

The signature of m is a subsignature (§8.4.2) of every method's signature in M.

m is return-type-substitutable (§8.4.5) for every method in M.

请注意,它表示 public 实例。当您取消注释 clone() 时,这是一个 not 与 public 实例方法具有相同签名的方法,因为 clone()Object 是一个受保护的实例方法。因此,您的 clone() 方法将满足条件。你不能对 equals() 说同样的话,因为 equals()Object 中的一个 public 实例方法。也就是说,这条规则所引用的集合M是空的,因此必须在这个集合中的方法m不存在。

JLS 中有几段评论解释了为什么他们决定以不同的方式对待 clone()