Java 8 Functional Interface By Examples

Java 8 Functional Interface concept was introduced by Java to support Lambda Expressions which are very similar to Scala with the fact that you can assign Lambda Expression to a Functional Interface. Let’s explore the details.

What is Functional Interface in Java 8?

Similar to the Marker Interface which has no methods, Functional Interface is the interface having Single Abstract Method declared in it. This method is referred as Functional Method.

Why Functional Interface is required in Java 8?

Java 8 is a major step towards implementing concepts of Functional Programming in Java language. In order to provide the support of Syntactic Sugar same as other Functional Languages (like Scala) Java has introduced Lambda Expressions. And functional interfaces are the key components for the compact and expressive syntax of Lambda Expressions in Java 8.

For compile time validation Java 8 has added new annotation @FunctionalInterface for Functional Interfaces. This annotation is optional and the code is valid even if the annotation is not placed.

All the interfaces with only single (abstract)method in earlier versions of Java are by default becomes Functional Interfaces. This is how Java 8 provides backward compatibility with Functional Interfaces like java.lang.Runnable, java.util.concurrent.Callable, java.awt.event.ActionListener etc.

Let’s have a popular example of java.awt.event.ActionListener interface which prints label of the Button.

In earlier versions of Java, programmer have to write the implementation of Interface using anonymous class as below,

As we all know now java.awt.event.ActionListener is inherently a Functional Interface in Java 8 and new code can be written as below using Lambda Expression.


Final Notes on Functional Interfaces:

  • It must have only one abstract method
  • It may contain one or more default methods
  • Annotation @FunctionalInterface is not mandatory it is just for compiler to identify functional method
  • It can be used as a reference of a Java Lambda Expression

Java 8 comes up with some of the new functional interfaces defined under java.util.Function package which can frequently be used with Lambda Expressions.

Thank you readers for you valuable time…..!!!!!

Leave a Reply

Notify of