Java 8 Functional Interfaces

In my previous blog I have explained about what is Lambda expression which is introduced in Java 8. But in order to call the lambda expression, you need the functional interface.

A lot of people say that functional interface introduced in Java 8. I am not agree with that. Have you heard about the “Single abstract method concept” ? This concept was not introduced in Java 8 .

This concept is about, your interface can have only one abstract method.
This is very important. It doesn’t mean that interface cannot have more than one method. It can only contain one abstract method. Indirectly that means functional interface can have multiple methods(default, static). But those should not be abstract.

Before Java 8, we had Runnable interface and Closable interface which are introduced in java 7. The Runnable interface has only one method which is named as run and Closable interface also has only one method which is named as close. Hence this means we had this concept before. But it was not properly named as a functional interface.

Now Let’s see how this functional interface can be used,

Any given interface, if it has only one single abstract method, we call it as a functional interface. The advantage is you can use a lambda expression along with this functional interface.

Before Lambda expression coming, if we have an interface, we have to create a class to implement that interface and then we call that class. Now we remove all those intermediate parts and we have an interface which is a functional interface and we just call that functional interface through lambda expression without having a specific separate implementation.

But after one or two years, if someone add another abstract method to that same functional interface then all the lambda expressions will fail since that is not a functional interface anymore.

Java 8 has introduced is a new annotation called @FunctionalInterface. When you put that annotation on top of the class, compiler knows this is a functional interface. That means the compiler knows this class can only have a single abstract method. If you add a second abstract method then compiler will complain you that compiler will not compile the program. It will say that this is a functional interface and you can’t add abstract methods anymore.

Let’s see an example code,

@FunctionalInterface
public interface Vehicle {

void park(); //only one abstract method

default void start(){
System.out.println("Default method");
};

static void stop(){
System.out.println("Static method");
}
}

I hope you got a clear idea about what is a functional interface. Thank you!!