Functional Interfaces in Java


Create a Java program to demonstrate the use of a functional interface with a single abstract method

  • Calculator is a functional interface defined with the @FunctionalInterface annotation, indicating that it has exactly one abstract method.
  • Two lambda expressions are used to provide implementations for the calculate method of the Calculator interface: one for addition and one for subtraction.
  • In the main method, instances of the Calculator interface are created using lambda expressions.
  • These instances are then used to perform addition and subtraction operations, demonstrating the use of lambda expressions to provide behavior to functional interfaces.

Source Code

@FunctionalInterface
interface Calculator
{
	int calculate(int a, int b);
}
 
public class Main
{
	public static void main(String[] args)
	{
		Calculator addition = (a, b) -> a + b;
		Calculator subtraction = (a, b) -> a - b;
 
		System.out.println("Addition : " + addition.calculate(5, 7));
		System.out.println("Subtraction : " + subtraction.calculate(10, 4));
	}
}

Output

Addition : 12
Subtraction : 6

Example Programs