Functional Interfaces

Functional Interfaces are interfaces which have only one abstract method. There are many functional interfaces in Java API like here I have mentioned few examples:

//java.util.Comparator
public interface Comparator<T>{
  int compare(T o1, T o2);
} 
public interface Runnable{ void run();} // java.lang.Runnable
public interface Callable<V>{ V call(); }// java.util.concurrent.Callable

Functional interfaces can also have default methods,Default methods are basically a method with a body that provides some default implementation for a method in case its not implemented.

Signature of abstract method present in Functional Interface can describe the signature of a lambda expression. In other words what I mean to say is Lambda expression lets you provide the implementation of the abstract method of the functional interface(An instance of concrete implementation of the functional interface) . Lets see below example from Runnable Interface which is a functional interface.

Runnable r = () -> {System.out.println("Hello World");}
Runnable r1 =  new Runnable(){ public void run(){System.out.println("Hello World");}
};

Check this quiz to answer few lambda questions

What is @FunctionalInterface annotation?

This annotation tells the compiler that the interface is intended to be a functional interface, this annotation is not mandatory for interface to act as functional interface but its good practice to use it when an interface is designed for that purpose. you can think of it like @Override notation to indicate method is overridden.

Like below I have added 2 abstract methods in interface annotated with FunctionalInterface and compiler will give compilation error if we add extra abstract method(test2)

Functional Interfaces are useful as we can pass the behaviour using them and lambda expression. Check below code how lambda and functional Interface helps us to dynamically pass the behaviour

Here we have created Functional Interface ProcessName which does some processing on the name passed as an argument

Now we are passing different behaviour runtime using lambda which is binded to functional interface abstract method. Any client of method getName can pass its own implementation of method using lambda.

Remember, lambda expressions let you provide the implementation of the abstract method of a functional interface directly inline, and they treat the whole expression as an instance of a functional interface.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *