What are the rules for a functional interface in Java?

Java 8Object Oriented ProgrammingProgramming

A functional interface is a special kind of interface with exactly one abstract method in which lambda expression parameters and return types are matched. It provides target types for lambda expressions and method references.

Rules for a functional interface:

  • A functional interface must have exactly one abstract method.
  • A functional interface has any number of default methods because they are not abstract and implementation already provided by the same.
  • A functional interface declares an abstract method overriding one of the public methods from java.lang.Object still considered as functional interface. The reason is any implementation class to this interface can have implementation for this abstract method either from a superclass or defined by the implementation class itself.

Syntax

@FunctionalInterface
interface <interface-name> {
   // only one abstract method
   // static or default methods
}

Example

import java.util.Date;

@FunctionalInterface
interface DateFunction {
   int process();
   static Date now() {
      return new Date();
   }
   default String formatDate(Date date) {
      return date.toString();
   }
   default int sum(int a, int b) {
      return a + b;
   }
}
public class LambdaFunctionalInterfaceTest {
   public static void main(String[] args) {
      DateFunction dateFunc = () -> 77;      // lambda expression
      System.out.println(dateFunc.process());
   }
}

Output

77
raja
Published on 17-Jan-2020 12:50:38
Advertisements