Java Functional Interfaces
An Interface that contains exactly one abstract method is known as functional interface.
It is a new feature in Java, which helps to achieve functional programming approach.
It can have any number of default, static methods but can contain only one abstract method. It can also declare methods of object class.
Functional Interface is also known as Single Abstract Method Interfaces or SAM Interfaces.
Functional Interface can have only one functionality to exhibit.
Some Built-in Java Functional Interfaces
There are many interfaces that are converted into functional interface. All these interfaces are annotated with @FunctionalInterface. These interfaces are as follows –
Runnable –> This interface only contains the run() method.
Comparable –> This interface only contains the compareTo() method.
ActionListener –> This interface only contains the actionPerformed() method.
Callable –> This interface only contains the call() method.
WRITE A JAVA CODE USING CONCEPT OF FUNCTIONAL INTERFACE
package com.java.lamda.demo;
interface Calculator {
// CASE 1
/* void switchOn(); */
// CASE 2
/* void sum(int input); */
// CASE 3
int substract(int i1, int i2);
}
public class CalculatorImpl {
public static void main(String[] args) {
//Only one case works at a time
// ---------------------------------------------------------------------------------------
// CASE 1
/*
* Calculator calculator = () -> System.out.println("Switch On");
* calculator.switchOn();
*/
// ---------------------------------------------------------------------------------------
// CASE 2
/*
* Calculator calculator = (input) -> System.out.println("Sum : " + input);
* calculator.sum(394);
*/
// ---------------------------------------------------------------------------------------
// CASE 3
Calculator calculator = (i1, i2) -> {
if (i1 > i2) {
return i1 - i2;
} else {
return i2 - i1;
}
};
System.out.println(calculator.substract(8, 20));
}
}
CONSOLE
12
Comments
Post a Comment