×

Functional Interface in Java 8

A brief introduction to Interface in Java:

Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or more abstract methods inside an interface. From Java 8 onwards we can also declare default as well as the static methods inside the interfaces.

An interface is declared with the keyword “interface”. It is implemented inside the class using the keyword “implements”. The main motive behind introducing the interfaces is to achieve the functionality like multiple inheritance and to reduce the interdependencies among different classes in Java.

The advantages of the interface over inheritance are discussed below:

1. To achieve the multiple inheritance:

Java does not directly support multiple inheritance. We cannot declare a child class that can inherit more than one parent class. This will give a compile time error. Let us try to understand this with the help of the programming illustration provided below.

/*A program to show that Java does not support multiple inheritance.*/

class A
{
   void method()
   {
      System.out.println("Class A");
   }
}
class B
{
   void method()
   {
      System.out.println("Class B");
   }
}


/*Trying to inherit two parent classes A and B */
class C extends A,B
{
   
}
//The main method
class Main
{
   public static void main(String args[])
   {
      C object=new C();
      object.method();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Main.java:17: error: '{' expected
class C extends A,B
                 ^
1 error

Why Java does not support multiple inheritance?

In the above program, we got a compile time error. It is proved that Java does not support multiple inheritance. Let us try to understand why does the multiple inheritance is declared illegal in Java.

In this program, we have created an object of the C class and tried to call the function “method”. Now, class C inherits two classes, that is, class A and class B. Both the parent class have the function named “method” inside them. Now when we will try to call the function “method” the compiler will get confused, it will not understand which function to call, the function “method” of class A or the function “method” of class B. Hence Java developers collaboratively decided to declare multiple inheritance illegal in Java.

How can we achieve multiple inheritance using the interface?

/*Java program to achieve multiple inheritance in Java using the interfaces*/

interface A
{
   abstract void show();
}
interface B
{
   abstract void show();
   abstract void display();
}
class C implements A,B
{
   public void show()
   {
      System.out.println("Calling the abstract method show() from class A.");
   }
   public void display()
   {
      System.out.println("Calling the abstract method display() from class B.");
   }
}
class Main
{
   public static void main(String args[])
   {
      C object=new C();
      object.show();
      object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Calling the abstract method show() from class A.
Calling the abstract method display() from class B.

In the above program, we have show() method inside both the interfaces. But as the methods are abstract, we can only declare the implementation of those methods inside the class that implements the interface. In our case, the class is named C. Thus, if we create an object of C now, in the main class, and try to call the show method, unlike the previous case, this time the compiler will not get confused about which method to call because the implementation of both the show() method is same.

Hence, it is clear that with the help of interfaces we can achieve multiple inheritance in Java. If we declare the method name inside the interfaces, that is, declare abstract method inside interface and explain its implementation inside the class implementing the interface, then there is no chance of compilation error because it is very much clear to the compiler that which implementation it should show as an output.

2. The interface helps to achieve loose coupling:

The interface helps to reduce the interdependencies between the components of a system. The main problem with inheritance is the tight coupling. With the help of the interface, we can achieve loose coupling. Let us demonstrate the following with the help of Java programs.

/*Java program to show inheritance in java*/

class A
{
   void display()
   {
       System.out.println("Here we go.");
   } 
}
class B extends A
{
   
}
class C extends B
{
   
}
class Main
{
   public static void main(String args[])
   {
      A obj=new A();
      B obj1=new B();
      C obj2=new C();
      System.out.println("Printing display method inside A:");
      obj1.display();
      System.out.println();
      System.out.println("Printing display method inside B:");
      obj1.display();
      System.out.println();
      System.out.println("Printing display method inside C:");
      obj1.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Printing display method inside A:
Here we go.


Printing display method inside B:
Here we go.


Printing display method inside C:
Here we go.

In the 1st program, we have a parent class A with a method display() defined inside it. Here all the child classes, that is, class B and class C, inherits the parent class A. Thus the method display() also gets inherited.

Now, when we create an object of class B and try to print the display() method we get the display() method defined in class A. This is the same in the case of class C. when we create an object of class C and try to print the display() method we get the same display() method defined in class A.

Suppose later in future, we want to change the display method inside class A, provided, we do not want to change the display method inside the inherited class. Is it possible to do so? Yes, it is possible. But imagine the complexity. If it is a real world project with thousands of classes inheriting a parent class, for a minute change in parent class we need to override all the hundred and thousands of methods that inherits the parent classes. The money and time that will get wasted in this process is the sky limit.

/*Java program to show how we can achieve loose coupling using the interface in java*/

interface A
{
  void numbers();
}
class B implements A
{ 
   public void numbers()
   {
      System.out.println("Implementation of the method numbers() inside class B:");
      System.out.println("Hello B");
      System.out.println();
   }
}
class C implements A
{
    public void numbers()
   {
      System.out.println("Implementation of the method numbers() inside class C:");
      System.out.println("Hello C");
      System.out.println();
   }
}
class D implements A
{
    public void numbers()
   {
      System.out.println("Implementation of the method numbers() inside class A:");
      System.out.println("Hello D");
      System.out.println();
   }
}
class Main
{
   public static void main(String args[])
   {
      System.out.println("Achieving loose coupling through an interface.");
      System.out.println();
      B obj=new B();
      C obj1=new C();
      D obj2=new D();
      obj.numbers();
      obj1.numbers();
      obj2.numbers();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Achieving loose coupling through an interface.


Implementation of the method numbers() inside class B:
Hello B


Implementation of the method numbers() inside class C:
Hello C


Implementation of the method numbers() inside class A:
Hello D

Hence, it is possible to achieve loose coupling with the help of interface as all classes are independent of one another.

Introduction to functional interface

From the above programs, it is clear that with the help of the interface we get a lot of control over our methods. As we do not describe the characteristics of the abstract method inside the interface we get an opportunity to describe the characteristics of the abstract method inside the class implementing the interface. In fact, it is necessary to override the abstract method inside the class implementing the interface. Hence, in case, we want to make any changes inside the interface, there are no tight coupling issues, that is, overriding the hundred and thousands of methods in each and every class, since, all the classes are independent of one another.

Java 8 brought a lot of functionalities and new features. The interface in Java encountered some major and revolutionary changes. For the first time, in addition to the abstract method, the declaration of the static and default methods inside an interface was announced legal. The functional interface was defined for the first time.

Functional interfaces are those interfaces in Java that can have only one abstract method. In addition to an abstract method, they are free to have any number of default and static methods. The runnable interface in Java with the help of which we achieve multithreading and also the action listener interface, which contains the abstract method action performed, are some of the examples of the functional interfaces.

/* Java program to illustrate the general approach to override a method declared inside a functional interface with the help of implementing classes */

interface abc{
   public void show();
   static void print(){
      System.out.println("Static method print inside an interface abc.");
      System.out.println();
   }
   default void display(){
      System.out.println("default method display inside an interface abc.");
      System.out.println();
   }    
}
class xyz implements abc{
   public void show(){
      System.out.println("Overriden abstract method show within an interface abc with the help of implementing class xyz");
      System.out.println();
   }
}
public class Main{
   public static void main(String[] args){
      xyz obj=new xyz();
      obj.show();
      abc.print();
      obj.display();   
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Overriden abstract method show within an interface abc with the help of implementing class xyz


Static method print inside an interface abc.


default method display inside an interface abc.

/* Java program to illustrate how to override a method declared inside a functional interface with the help of the Anonymous class */

/*Declaring an interface named Anonymous with 2 abstract methods show and display*/
interface Anonymous
{
  void show();
  void display();
}
// The driver class
class Main
{
   public static void main(String[] args)
   {
      //Anonymous class implementation
      Anonymous object=new Anonymous()
      {
         /*Defining the abstract method show inside the anonymous class*/
         @Override
         public void show()
         {
           System.out.println("Overriden the show method with the help of the anonymous class.");
           System.out.println();
         }
        /*Defining the abstract method display inside the anonymous class*/
        @Override
         public void display()
         {
            System.out.println("Overriden the display method with the help of the anonymous class.");
            System.out.println();
         }
      };
        /*Calling the overridden methods show and display with the help of the object of the anonymous class*/
        object.show();
        object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Overriden the show method with the help of the anonymous class.


Overriden the display method with the help of the anonymous class.

Functional interface and lambda expression are correlated to one another. It was necessary to bring functional interface in picture because the Java developers were working on to improve code readability by avoiding lengthy boiler plate codes and came up with the idea of lambda expression. These may seem confusing at the first place but in this section, we will discuss everything like why we can’t use normal interface with lambda expression? but before this let us revise the lambda expression in Java.

The main motive behind learning lambda expression is that it increases readability by cutting down the size of the program. The whole concept of lambda expression somewhat revolves around the functional interface. The lambda expression in java only works with the functional interface.

Lambda expression is an anonymous function that does not have a name and does not belong to any class. It is an enhanced version of an anonymous class. It provides a transparent and straightforward way to write our code and increases the code readability.

The syntax for the lambda expression is:

parameter -> expression body

The arrow operator was introduced in java through the lambda expression. It divides the code into two parts, that is, the parameters and expression body.

The characteristics of lambda expression are listed below:

  • Type declaration is not mandatory in the lambda expression.
  • It is not necessary to write the method name while using a lambda expression.
  • The parenthesis around parameters is optional.
  • We may or may not use the curly braces.
  • It is not necessary to use the return keyword with a lambda expression.

/* Java program to illustrate how we can easily override a method declared inside a functional interface with the help of the lambda expression */

/*Declaring an interface named lambda with one abstract method show and other default method display*/


interface Lambda
{
  void show();
  default void display()
  {
    System.out.println("This is the non abstract method inside the functional interface.");
  }
}
// The driver class
class Main
{
   public static void main(String[] args)
   {
      
      //Lambda expression implementation
      /*Overriding the abstract method inside the functional interface with the help of lambda expression*/
   Lambda object=()-> {System.out.println("Show method is overridden using a lambda expression.");
   System.out.println();
   };
   /*Calling the abstract method show and default method display.*/
   object.show();
   object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Show method is overridden using a lambda expression.


This is the non abstract method inside the functional interface.

Why do we need the functional interface to work with lambda expression?

We have already discussed the following:

  • Type declaration is not mandatory in the lambda expression.
  • It is not necessary to write the method name while using a lambda expression.
  • The parenthesis around parameters is optional.
  • We may or may not use the curly braces.
  • It is not necessary to use the return keyword with a lambda expression.

Hence, if we have more than one abstract method then the compiler will get confused about which method to override and hence, we will get the compile time error.

/*Java program to show the importance of functional interface for implementing the lambda expression*/

interface Lambda
{
  void show();
  void show2();
  default void display()
  {
    System.out.println("Trying to implement lambda expression with non functional interfaces.");
    System.out.println();
  }
}
// The driver class
class Main
{
   public static void main(String[] args)
   {
      
      //Lambda expression implementation
      /*Trying to Override the abstract methods with the help of lambda expression*/
   Lambda object=()-> {System.out.println("The method is overridden using a lambda expression.");
   System.out.println();
   };
   /*Calling the abstract method show and default method display.*/
   object.show();
   object.display();
   }
}

Output-

Microsoft Windows [Version 10.0.22000.318]

(c) Microsoft Corporation. All rights reserved.

C:\Users\USER\Desktop\JTP Folder>javac Main.java //Compile

C:\Users\USER\Desktop\JTP Folder>java Main //Run

Main.java:22: error: incompatible types: Lambda is not a functional interface
   Lambda object=()-> {System.out.println("The method is overridden using a lambda expression:");
                 ^
    multiple non-overriding abstract methods found in interface Lambda
1 error

Related Topics

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Java HashMap

Java HashMap extends AbstractMap and implements Map interface. It is the collection of multiple entries where an entry consists of key and value pair. The HashMap can contain only one...

7 minutes read.

Vectors in Java

Vector Class We may make resizable arrays comparable to the ArrayList class using the Vector class, which implements the List interface. A vector is similar to a dynamic collection that can...

4 minutes read.

Client Server Program in Java

Client Server Program in Java The client and server are the two main components of socket programming. The client is a computer/node that request for the service and the server is...

7 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Java LDAP Authentication

WHAT IS LDAP? Clients can communicate with directory services by sending requests and receiving responses using the Lightweight Directory Access Protocol (LDAP). The term "LDAP server" refers to a directory service...

7 minutes read.

Why we use static in Java

Many reserved keywords in Java cannot be used as variable names or identifiers. Java uses static keywords frequently because of its effective memory management system. In most cases, you must...

3 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Differences and Similarities between HashSet, LinkedHashSet and TreeSet in Java

HashSet Class: The HashSet is a class that executes the Setpoint of interaction. It is utilised to store the items in a hashtable; a hashtable is an information structure which holds...

10 minutes read.

Types of Assignment Operators in Java

In this tutorial, we are going to study assignment operators and their types in Java language. Before proceeding to the types, let us know the term ‘assignment operator’.  The assignment...

5 minutes read.

Java extend multiple classes

In Java, what does extend mean? One of several Java inheritance keywords is extended, meaning we pass all or most of the Parent class's characteristics through to the Child class. The...

3 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Java Program to Add Digits Until the Number Becomes a Single Digit Number

We will develop Java programme that increase a number's digit count in order to reduce it to one. The issue is also known as the digit root problem. Example Consider the case where...

3 minutes read.