What is Functional Interface?
Functional
Interfaces: An interface is called a functional interface if it has a single
abstract method irrespective of the number of default or static methods.
- Annotation @FunctionInterface used(optional).
- It should have only 1 abstract method.
- Two abstract methods give compilation error(given annotation is written @FunctionalInterface).
- It can have any number of default or static methods.
Why it is used and what are the benefits?
- Earlier we used to use Anonymous class to serve the purpose of inline method implementation. This approach with an anonymous class is tedious, lengthy, and not easy to read.
- Functional Interface helps us achieve the same benefit of anonymous class but in a concise form.
Below is
the example of Anonymous class and functional interface serving the same
purpose.
FunctionalInterfaceImpl
FunctionalInterfaceDemo
As
we can see from the above examples, to implement different behavior of doOperation
method, Lamda expression approach looks more concise and easy to read than
Anonymous Class.
No comments:
Post a Comment