How to use functional interface in Java
In this tutorial, I will introduce you to the term interface in Java. Interface can have methods and variables like class, but the methods are by default abstract. It does not have a body. We use ‘interface’ keyword to declare it. We can achieve complete data abstraction with the use of interface. So let’s start learning functional interface in Java.
Syntax of interface in Java
The syntax of the interface is :
interface <inter_name> { // declare constants // declare methods that abstract }
We can achieve multiple inheritance with the help of interface. We use interfaces instead of abstract classes because interface variables are final, public and static. In Java 8, we are introduced to a functional interface. A functional interface contains only one abstract method. In Java 8, Lambda expressions are used to represent it. Let us see how :
//Implementing functional interface using lambda expressions class T1 { public static void main() { //creating the object using lambda expression new Thread( ()-> {System.out.print("Hello World!");}).start(); //prints "Hello World!" } }
The above code will print Hello World!
Output:
Hello World!
User Defined functional interface in Java
Let us try another example to demonstrate User Defined functional interface.
//implementing a user defined functional interface using lambda expression @FunctionalInterface //functional interface annotation interface Cube { int calculate(int x); } class Test { public static void main(String args[]) { int a = 3; // lambda expression to define the calculate method Cube s = (int x)->x*x*x; // parameter passed and return type must be same as defined in the prototype int ans = s.calculate(a); System.out.println(ans); } }
The output is as follows:
27
You can also check this out Using Interface in Java with an Example
Leave a Reply