Functional Interfaces in Java

We’ve already mentioned Functional interfaces in Java, and in this tutorial, we will discuss them in more detail.


What is a Functional Interface in Java?

A Functional interface contains only one abstract method, a method that doesn’t have a body.
In addition, it can have many default and static methods, methods that contain implementations.

Since Java 8, we use @FunctionalInterface annotation to annotate such interfaces.
This annotation is optional.

Example of one Functional interface in Java:

 @FunctionalInterface
 public interface Runnable {
   public abstract void run();
 }


Example of Functional interface that has default and static methods also:

@FunctionalInterface
interface MyFunctionalInterface {

  int printNumbers(int number1, int number2); // we don't need to put abstract keyword

  default void printText(String text) {
    System.out.println(text);
  }

  static void printText(String text, boolean enabled) {
    if (enabled) {
      System.out.println(text);
    } else {
      System.out.println("Not enabled.");
    }
  }
}


How to implement a Functional interface?

We can implement a Functional interface with a Lambda expression.

Let’s create one Functional interface:

 @FunctionalInterface
 interface Signable {
   void signDocument(String documentName);
 }


Now let’s implement it with Lambda:

@FunctionalInterface
interface Signable {
  void signDocument(String documentName);
}

class Test {

  public static void main(String[] args) {
    Signable signable = (name) -> {
      System.out.println("The document with name '" + name + "' has been signed.");
    };
    signable.signDocument("Taxes");
  }
}

Output: The document with name 'Taxes' has been signed.


In Java 8, new Functional interfaces got introduced.

We have 4 primary interfaces as part of the java.util.function package (see more here: java.util.function):

  1. Consumer
  2. Predicate
  3. Function
  4. Supplier

We will cover each of them in upcoming lessons.

That’s it!

 

Leave a Reply

Your email address will not be published.