What are the rules for a functional interface in Java?


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
raja

e

Updated on: 14-Jul-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements