Core Java

Java 8 Functional Interfaces Introduction Example

Hello readers! In this tutorial, we will learn the amazing feature of Java 8 Functional Interfaces.

1. Introduction

To achieve the benefits of functional programming in Java, JDK developers introduced Functional Interfaces/Single Abstract Method (SAM) Interfaces in Java 8 programming.

  • A functional interface is an interface that has only one abstract method
  • A functional interface can have multiple default and static methods
  • @FunctionalInterface annotation ensures that the interface will be treated as a functional interface. This annotation throws a compile-time error if the primary condition for SAM interfaces is not met
  • Callable, Runnable, ActionListener, Comparable, Consumer, Supplier, Predicate, etc. are some examples of functional interfaces introduced in Java 8
  • Syntax:
    1
    2
    3
    4
    5
    @FunctionalInterface
    public interface Interface1 {
        public abstract void method1();
        default void method2() { System.out.println("Hello World!"); }
    }
  • A functional interface can override the methods of java.lang.Object class
    1
    2
    3
    4
    5
    6
    7
    8
    @FunctionalInterface
    public interface Interface2 {
        public abstract void method2();
        // java.lang.Object class methods.
        boolean equals(Object o);
        string toString();
        int hashCode();
    }

1.1 Inheritance & Functional Interfaces

  • If a normal interface extends a functional interface and the child interface does not contain any method, then child interface is also a Functional Interface
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @FunctionalInterface
    interface Interface1 {
        public void method1();
    }
     
    @FunctionalInterface
    interface Interface2 extends Interface1 {   // Interface2 is also a child interface.
         
    }
  • In the child functional interface, we can define the exact same method as in the parent interface
    1
    2
    3
    4
    5
    6
    7
    8
    9
    @FunctionalInterface
    interface Interface1 {
        public void method1();
    }
     
    @FunctionalInterface
    interface Interface2 extends Interface1 {
        public void method1();      // No compile-time error as we have defined the exact same method as in parent interface.
    }
  • If the child interface is a functional interface, we can’t define any new abstract methods. If the former is true, it will result in a compile-time error. However, we can define multiple default and static methods
    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17
    @FunctionalInterface
    interface Interface1 {
        public void method1();
    }
     
    @FunctionalInterface
    interface Interface2 extends Interface1 {
        public void method1();
         
        default void method2() {
            System.out.println("method2()");
        }
         
        static void method3() {
            System.out.println("method3()");
        }
    }
  • If the child interface is not a functional interface, we can define any number of abstract, default, and static methods

1.2 Advantages of Functional Interfaces

  • Provides compile-time code checking
  • Helps in lambda expressions instantiation and avoiding anonymous classes implementation

To start with this tutorial, we are hoping that users at present have their preferred IDE and JDK 1.8 installed on their machines. For easy usage, I am using Eclipse IDE.

2. Java 8 Functional Interfaces Introduction Example

Firstly, let us review the project structure that has an interface and class to demonstrate a functional interface in Java 8.

Java 8 Functional Interfaces - Project Structure
Fig. 1: Project Structure

2.1 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Java 8 Functional Interfaces - Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ check-box and just click on next to proceed.

Java 8 Functional Interfaces - Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Java 8 Functional Interfaces - Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created.

3. Application Building

To create a new class, right click on the src/main/java folder, New -> Class. Fill in the details about the package and class name as shown in Fig. 5 and click finish.

Java 8 Functional Interfaces - Creating a Class
Fig. 5: Creating a Class

3.1 Functional Interface in Play

Let us add some code to the FunctionalInterface.java class.

FunctionalInterface.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package jcg.functionalinterface.example;
 
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
 
interface MyRectangle {
    int calculateVolume(int length, int height, int width);
}
 
public class FunctionalInterface {
 
    static List countries = Arrays.asList("America", "India", "Russia", "China", "Japan", "Indonesia");
 
    public static void main(String[] args) {
 
        // Example #1 - Implementing user-defined functional interface using lambda expression.
        MyRectangle rectangle = (int length, int height, int width) -> length * height * width;
        System.out.println(rectangle.calculateVolume(5, 5, 5));
 
        // Example #2 - Runnable functional interface using old implementation (i.e. anonymous class).
        Runnable runnableUsingAnonymousClass = new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello World from Anonymous Class!");
            }
        };
        Thread myThread1 = new Thread(runnableUsingAnonymousClass);
        myThread1.start();
 
        // Example #3 - Runnable functional interface using lambda expression.
        Runnable runnableUsingLambda = () -> {
            System.out.println("Hello World from Lambda Expression!");
        };
        Thread myThread2 = new Thread(runnableUsingLambda);
        myThread2.start();
 
        // Example #4 - Predicate functional interface.
        Predicate predicate = (name) -> name.startsWith("I");
        for(String name : countries) {
            if(predicate.test(name))
                System.out.println(name);
        }
    }
}

4. Run the Application

Right click on the FunctionalInterface.java class, Run As -> Java Application. The class will be executed and the output will be printed in the ide console.

Output

1
2
3
4
5
6
7
8
125
 
Hello World from Anonymous Class!
 
Hello World from Lambda Expression!
 
India
Indonesia

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we had an in-depth look at Functional Interfaces in Java 8. Developers can download the sample application as an Eclipse project in the Downloads section.

6. Download the Eclipse Project

This was an example of Java 8 Functional Interfaces.

Download
You can download the full source code of this example here: Java 8 Functional Interfaces Introduction Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button