Java 8 functional interface example

In this post , we are going to see about functional interface in java. It is closely related to java lambda expressions.
Functional interfaces are those interfaces which have only one abstract method, it can have default methods, static methods and it can also override java.lang.Object class method.
There are many functional interfaces already present.
For example: Runnable , Comparable.
You can implement functional interfaces using lambda expressions.
Lets understand with classic example of Runnable:
When we need to create a Thread and pass anonymous Runnable interface, we can do it as follow.

Above method is old method of creating thread. As we have single abstract method in Runnable interface , we can consider it as functional interface, hence we can make use of lambda expression.

Lets see an example of functional interface,

Java can itself identify Functional Interface but you can also denote interface as Functional Interface by annotating it with @FunctionalInterface. If you annotate @FunctionalInterface, you should have only one abstract method otherwise you will get compilation error.

When you run above program, you will get below output:

Add Comment