下面的接口(interface)是 Java 8 中的有效功能接口(interface)吗?
@FunctionalInterface
interface Normal{
public abstract String move();
public abstract String toString() ;
}
为什么它不给我一个编译时错误?
最佳答案
Alok 引用的内容是正确的,但他忽略了一些事情,这使得他的最终答案(代码无效)是错误的:
接口(interface)有一种方法String toString()
每个类都已经实现,从 Object
继承. IE。声明的接口(interface)方法已经有一个实现,类似于默认方法。因此,没有编译错误和Normal
可以用作我的MCVE中所示的功能接口(interface):
package de.scrum_master.stackoverflow;
@FunctionalInterface
interface Normal {
String move();
String toString();
}
顺便说一句,无需将接口(interface)方法声明为
public
因为他们总是这样。 abstract
也是如此.package de.scrum_master.stackoverflow;
public class NormalApp {
static void doSomething(Normal normal) {
System.out.println(normal.move());
System.out.println(normal.toString());
}
public static void main(String[] args) {
doSomething(() -> "xxx");
}
}
如果您运行驱动程序应用程序,您将看到以下控制台日志:
xxx
de.scrum_master.stackoverflow.NormalApp$$Lambda$1/1530388690@28c97a5
现在,如果您更改方法名称
toString
到别的东西,例如toStringX
,您会看到由于 @FunctionalInterface
编译类时出现预期的错误消息:Unexpected @FunctionalInterface annotation
de.scrum_master.stackoverflow.Normal is not a functional interface
multiple non-overriding abstract methods found in interface de.scrum_master.stackoverflow.Normal
关于java - 为什么我的@FunctionalInterface 使用两种方法没有编译错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60359816/