Is it mandatory to mark a functional interface with @FunctionalInterface annotation in Java?


An interface defined with only one abstract method is known as Functional Interface. It's not mandatory to mark the functional interface with @FunctionalInterface annotation, the compiler doesn't throw any error. But it’s good practice to use @FunctionalInterface annotation to avoid the addition of extra methods accidentally. If an interface annotated with @FunctionalInterface annotation and more than one abstract method then it throws a compile-time error.

Syntax

@FunctionalInterface
interface interface_name {
   // only one abstarct method declaration
}

Example

@FunctionalInterface
interface Shape {
   void printArea(int x);
}
public class SquareTest {
   public static void main (String args[]) {
      Shape square = (x) -> {     // Lambda Expression
         System.out.println("The area of a square is: "+ x*x);
      };
      square.printArea(7);
   }
}

Output

The area of a square is: 49

Updated on: 10-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements