Why Functional Interfaces in Java 8 have one Abstract Method?

后端 未结 3 1618
时光取名叫无心
时光取名叫无心 2020-11-28 11:13

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

相关标签:
3条回答
  • 2020-11-28 11:37

    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.

    0 讨论(0)
  • 2020-11-28 11:40

    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.

    0 讨论(0)
  • 2020-11-28 11:57

    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.
    0 讨论(0)
提交回复
热议问题