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

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 16-Dec-2019 11:54:31
Advertisements