- Functional interface are interfaces with only one abstract method in it.
- Can have multiple Static and default methods
- Default methods can be overriden
- Default cannot be made final
- Dimond problem can occur since two interfaces can have same default methods hence you need to override the default method for your code to compile
@FunctionalInterface
annotation is added so that we can mark an interface as functional interface.
It is not mandatory to add this annotation to our interface but it is best if we do because if some one creates a lambda expression out of the interface and later some one adds method to that interface then those lambda expression will stop working.
Note : Concrete methods in a interface does not count, i.e there is 1 abstract method and many concrete methods in a interface; it is still a Functional Interface
@FunctionalInterface public interface MathDemo { public int add(int x,int y); }
- Note Functional Interface can contain methods of Object class in abstract format, it is allowed
@FunctionalInterface public interface Demo7 { int tempFunction(); boolean equals(Object obj); int hashCode(); }
- Java 8 comes with new package java.util.function which provides 43 interfaces which will help you create Functional interfaces providing target types for lambda expressions and method references.
- This some of the functional interfaces provided by java 8 so that we don’t create just them manually every time we use lamdas
All the 43 interfaces can be divided into 4 categories : java doc for methods
- Supplier (Parameter as object and Returns the same type of Object)
- Consumer/Bi-Consumer (Parameter as an object but does not return anything)
- Predicate/Bi-Predicate (Parameter as object but returns boolean)
- Function/Bi-Function (Parameter as object and returns a different object)
Note : There is not BiSupplier since supplier supplies the same type that is given as input since java cannot return two values from a method there is not Bi Supplier