Functional interfaces: Why only one abstract method?


Hello! Why can functional interfaces contain only one abstract method? What is the reason for this? And why it was impossible to make several methods (with different parameters) for interacting with lambda expressions in one function. the interface?

Author: Виталина, 2014-08-30

1 answers

This solution is based on the concept of a function. Formally, a function has a name, a list of parameters, and a return value. If the function has the same name and a different list of parameters or a different return value, then it is a different function. So it is logical to have one instance of the interface with one method per function (after all, the function can only be applied, and nothing more).

The Java language does not have functions as independent entities, so they are emulated by using interfaces with one an abstract method (Single Abstract Method, SAM).

Thus, if you want to define a function of some type (Function, Consumer, etc.), you only need to implement the method of the corresponding interface in a standard way or using a syntax for defining lambda expressions. In the second case, the compiler will be able to decide what type of functional interface to use (because a lambda function is often a parameter of a known method, and therefore a known one type), and which method of this interface should be called in the end (this is simple, because it is one).

 6
Author: a_gura, 2014-08-30 16:17:26