Java ProgramsOOPFunctional Interface

Functional Interface in Java

intermediate·  OOP  ·  Interfaces

Problem

A functional interface has exactly one abstract method, which makes it possible to implement it inline with a lambda expression instead of writing out a full class.

Define a functional interface with one method, and implement it using a lambda instead of a class.

Input
a = 5, b = 3
Output
Sum: 8

Java Program

Java
@FunctionalInterface interface Calculator { int operate(int a, int b); } public class FunctionalInterfaceDemo { public static void main(String[] args) { Calculator add = (a, b) -> a + b; // lambda supplies operate()'s body directly System.out.println("Sum: " + add.operate(5, 3)); } }

Output

Sum: 8

Core Logic

Since the interface has only one abstract method, a lambda expression can supply that method's body directly, without declaring a named class at all.

How It Works
  1. 1@FunctionalInterface marks Calculator as intended to have exactly one abstract method — the compiler flags an error if a second one is added later.
  2. 2interface Calculator declares just int operate(int a, int b);.
  3. 3(a, b) -> a + b is a lambda expression — its parameters and body implement operate directly, inferred from the interface's single method signature.
  4. 4add.operate(5, 3) calls the lambda exactly like it would call a real implementing class's method.
Calling add.operate(5, 3) runs the lambda's body, 5 + 3, printing "Sum: 8".
💡

Key Point: A lambda expression can only stand in for an interface if that interface has exactly one abstract method — that single-method requirement is exactly what 'functional interface' means.

Key Concepts

functional interfacelambda expression@FunctionalInterface

Related Programs