Que 1. What is FunctionalInterface in Java?
A functional interface is an annotation in Java introduced in JDK 8.
Found in java.util.function package
The functional interface exactly contains only one abstract method.
Single Abstract Method
Lambda Expression and Method reference
Readability and concise
When to use @FunctionalInterface
Use when you want concise code and want to use lambda expression or stream operation in that case we can go for @FunctionInterface.
To represent the instance of a functional interface lambda expressions are used.
What happens if you define more than one abstract method in @FunctionalInterface
If you are going to define more than one abstract method in a functional interface you will get compilation errors.
All methods inside the interface are abstract by default.
Only one abstract and n number of static and default methods can be defined under the functional interface.
What are some commonly used types of functional interfaces?
- Consumer:- argument accepted but did not return anything.
- Predicate:- Perform the test and return a boolean value.
- Supplier: does not take any argument but returns value.
- Function:- transfer argument into returnable value.
Why is a functional interface introduced in Java?
- Allow users to use lambda expressions.
- It allows users to use functional programming.
- The functional interface ensures that there is only one abstract method.
- Before java8, we had to implement these interfaces or create anonymous inner classes to implement methods.
Can a functional interface inherit/implement another interface?
A functional interface can’t extend and inherit another interface if it contains an abstract method.
However, a functional interface can be inherited if it contains only static and default methods in it.
If we have used @FunctionalInterface but did not declare any abstract method what will happen?
It will throw a compile-time error. Indicating that the target method is not found or no abstract method is found in the interface.