What is Functional Interface in Java 8?


A functional interface is an interface that has only one abstract method. They are bound to exhibit singular functionality. Runnable, Comparable and Predicate are a few examples of functional interfaces.

@FunctionalInterface Annotation is used to ensure that the functional interface can’t have more than one abstract method. Java 8 onwards, we can assign lambda expressions to functional interface objects.

Let us see how a user defined functional interface works out −

Example

 Live Demo

@FunctionalInterface
interface Cube {
   int compute(int x);
}
public class Example {
   public static void main(String args[]) {
      int p = 6;
      Cube c = r -> r * r * r; // lambda expression which defines the compute method
      int result = c.compute(p);
      System.out.println(result);
   }
}

Output

The output is as follows −

216

Updated on: 27-Jun-2020

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements