What is Functional Interface in Java 8?

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 03-Jan-2019 15:02:29
Advertisements