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