Why Functional Interfaces in Java 8 have one Abstract Method?

人盡茶涼 提交于 2019-12-17 07:33:30

问题


As we know in Java 8, the concept of functional interfaces are introduced. A Functional Interface has one abstract method and several default or static methods are possible.

But why should a Functional interface have only one abstract method? If Interface has more then one abstract method, why is this not a Functional Interface?


回答1:


The functional interface also known as Single Abstract Method Interface was introduced to facilitate Lambda functions. Since a lambda function can only provide the implementation for 1 method it is mandatory for the functional interface to have ONLY one abstract method. For more details refer here.

Edit -> Also worth noting here is that, a functional interface can have a default implementation in the interface. You will find a lot more details on the implementation on the link above.




回答2:


Functional Interface lets us call an object as if it were a function, which lets us pass verbs(functions) around our program rather than nouns(objects). Implementations of Functional Interface perform a single well-defined action, as any method should, with a name like run, execute, perform, apply, or some other generic verb.[1]

  1. Functional Programming Patterns in Scala and Clojure.



回答3:


If Java would have allowed having two abstract methods, then lambda expression would be required to provide an implementation of both the methods. Because, calling method won't know, which method to call out of those 2 abstract methods. It could have called the one which is not implemented. For example

If Java would have allowed this kind of functional interface

@FunctionalInterface
interface MyInterface {
    void display();
    void display(int x, int y);
}

Then on implementing the following would have not been possible.

public class LambdaExpression {
    public static void main(String[] args) {
        MyInterface ref = () -> System.out.print("It is display from sout");
        ref.display(2, 3);

    }
}

Since display(int x, int y) is not implemented, it will give the error. That is why the functional interface is a single abstract method interface.




回答4:


Writing Lamba expression meaning we are implementing the interface that is functional interface. It should have one abstract method because at the time of lambda expression, we can provide only one implementation at once. So in the code snippet posted in the below question, at any time we are giving only one implementation while declaring Lambda where we will have to implement for two abstract methods.

Why not multiple abstract methods in Functional Interface in Java8?



来源:https://stackoverflow.com/questions/23342499/why-functional-interfaces-in-java-8-have-one-abstract-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!