我正在阅读本教程中的 Java 功能接口
这是困扰我的具体代码:
public interface FunctionalInterfaceTest{
void display();
}
//Test class to implement above interface
public class FunctionInterfaceTestImpl {
public static void main(String[] args){
//Old way using anonymous inner class
FunctionalInterfaceTest fit = new FunctionalInterfaceTest(){
public void display(){
System.out.println("Display from old way");
}};
fit.display();//outputs: Display from old way
//Using lambda expression
FunctionalInterfaceTest newWay = () -> {System.out.println("Display from new Lambda Expression");}
newWay.display();//outputs : Display from new Lambda Expression
}
}
我不明白。有一个名为display()
. 它不做任何事情,也从未定义过。是的,我知道当您在功能接口中调用单个方法时,它会执行在其中创建的 lambda 表达式中的代码。
但这是我的问题;如果所有函数式接口本质上都只是运行 lambda 表达式,那么为什么不节省我们命名单个方法的时间,并使其永久化exe()
呢?如果它几乎没有添加任何内容,那么提供功能接口语法和自定义的意义何在。对我来说更好的语法是:
@FunctionalInterface MyInterface
MyInterface mine = () -> {System.out.print("Mine!!")}
mine.exe();
这更标准,更短,更容易理解。
这是一个绝妙的主意还是我错过了什么?