- Functional interfaces brings power of functional programming in Java
- Interfaces which contains one & only one abstract method
- It can contain other default & static methods (as many as required), but only one abstract method
- By adding @FunctionalInterface annotation for an interface, compiler will NOT let you add another abstract method in the interface
- If functional interface overrides one of public abstract methods on java.lang.Object, it will not count in interface's abstract methods as it WILL have implementation in Object class or elsewhere. For example, Comparator is functional interface and it has TWO abstract methods, comapre and equals, out of which equals method signature is matching with Object class' equals method
- Though @FunctionalInterface annotation is not mandatory, it is good practice to add the annotation, so that even other developers will not be able to add abstract method and break Lambdas or other codes
- Lambdas are shorthands for functional interfaces implementations i.e. Lambdas provides implementation of abstract method, returning functional interfaces
- Java 8 has also introduced a few reusable functional interfaces as follows Predicate, Consumer, Supplier, BiConsumer, Function, etc. check this out
- Other examples : Runnable (run), Comparator (compare)
Example:
package java8.functionalinterface;
public class FunctionalinterfaceDemo {
public static void main(String[] args) {
MyFunctionalInterface myFunctionalInterface1 = new MyFunctionalInterface() {
@Override
public void test() {
System.out.println("Implementation with Legacy Boiler Plate Code");
}
};
myFunctionalInterface1.test();
MyFunctionalInterface myFunctionalInterface2 = () -> System.out.println("Implementation with Lambda");
myFunctionalInterface2.test();
}
}
@FunctionalInterface
interface MyFunctionalInterface{
abstract void test();
}
No comments:
Post a Comment