What is Functional Interface in Java

March 14, 2020 | 1 comment

Introduction

Functional Interface

FunctionalInterface.java
Following interface is a functional interface since it has only one abstract method
@FunctionalInterface
interface MyComputeInterface {
  public int compute(int... a);
}

Functional Interface with default method.

MyComputeInterfaceWithDefault.java
Following interface is a functional interface since it has only one abstract method. It can have default methods though.
@FunctionalInterface
interface MyComputeInterfaceWithDefault {

  public int compute(int... a);

  default boolean isEven(int x) {
    return x / 2 == 0;
  }

}

Invalid Functional Interface

ComputeInterface.java
Following interface is invalid since it contains more than one abstract methods. Also as we have the @FunctionalInterface annotation applied, the compiler will complain stating ComputeInterface is not a functional interface.
@FunctionalInterface
interface ComputeInterface {
  public int add(int... a);
  public int average(int... a);
}

Note the @FuncationalInterface annotation is a runtime informative annotation that will make the compiler to complain if the interface contains more than one abstract methods.
Summary
  • A functional interface has only one abstract method but it can have multiple default methods.
  • @FunctionalInterface annotation is used to ensure an interface can’t have more than one abstract method. The use of this annotation is optional.
  • instances of functional interfaces can be created with lambda expressions, method references, or constructor references
  • Java provides out of the box Functional interfaces that we can use.

1 comment :

Please leave your message queries or suggetions.