Functional Interface in Java
Functional interface is a special type of interface which can have only one abstract method and any number of default methods.
To declare an interface a functional interface use @FunctionalInterface annotation.
Example:
@FunctionalInterface
interface Calculator{
int calculate(int a, int b);
}
class Add implements Calculator{
@Override
public int calculate(int a, int b){
return a+b;
}
}
Note: If we add another abstract method inside the Calculator interface, it will result into a compilation error.
- Best use of functional interface is with lambda expressions.
In Java there are the following important and widely used inbuilt functional interfaces are defined:
- Function<T, R>: represents a function that accepts one argument of type T and produces a result of type R
- Predicate<T>: represents a Boolean valued function which accepts one argument of type T and returns a Boolean
- Supplier<T>: represents a supplier which accepts nothing but returns a result of type T.
- Consumer<T>: represents an operation that accepts a single input argument and returns no result.
Comments
Post a Comment