Avijit Pramanik's Blog

Avijit Pramanik's Blog

Functional Interface in Java

 

 What is Functional Interface

A Functional Interface can have only one abstract method. Now the question can arise that why we need an interface which can have only one abstract method, the answer is, on every occasion we create an Interface for a purpose and that is to have multiple implementation for it which can be dynamically passed where the Interface reference is used. Functional Interface can also has the same ability in a greater way where we can pass any method which has the signature identical to the single abstract method that is contained by the Functional Interface. Since any method can be passed where the interface is used, so there is no need for creating unnecessary classes which need to implement that interface.

package com.avijit.blog;

// This is the functional interface which can have
// only one method signature.
@FunctionalInterface
interface IPrint {
    public void print(String data);
}

public class DataPrinter {
    
    // Function that take "Functional Interface" IPrint as one
    // argument and the data that needs to be printed as the other.
    public static void printData(IPrint iPrint, String data){
        iPrint.print(data);
    }
    
    // This is a function that's signature matches with the 
    // Functional Interfaces method's signature
    // public void print(String data);
    public static void printDataWithHi(String data){
        System.out.println("Hi: " + data);
    }
    
    // This is another function that's signature matches with the 
    // Functional Interfaces method's signature
    // public void print(String data);
    public static void printDataWithHello(String data){
        System.out.println("Hello: " + data);
    }
    
    public static void main(String[] args) {
        // Call printData function by using different 
        // function thats uses same signature of the 
        // Functional Interface function.
        
        // By using Lambda Expression
        printData(i -> printDataWithHi(i), "Test");
        // Or
        printData(DataPrinter::printDataWithHi, "Test");
        
        // Using another function which will produce different 
        // results.
        printData(i -> printDataWithHello(i), "Test");
        // Or
        printData(DataPrinter::printDataWithHello, "Test");
    }
}

//Output
Hi: Test
Hi: Test
Hello: Test
Hello: Test