What are Functional Interfaces?

A functional interface in Java is a special type of interface that has only one abstract method, meaning there is only one method to implement. It can also have default or static methods, but only one method must be abstract.

Java 8 also introduced a new annotation called @FunctionalInterface that you can use to mark your interface.

The @FunctionalInterface annotation is a special marker in Java that you place above an interface to tell the compiler that it is supposed to be a functional interface.

Here’s a simple and clear sample of a functional interface in Java:

@FunctionalInterface
interface Greeting {
    void sayHello(String name);
}

This interface has only one abstract method: sayHello(String name), which makes it a functional interface.

Using it with a Lambda Expression

public class Main {
    public static void main(String[] args) {
        Greeting greet = name -> System.out.println("Hello, " + name + "!");
        greet.sayHello("Alice");
    }
}

Output:

Hello, Alice!

Why Use @FunctionalInterface annotation?

  • It’s optional, but it’s good practice.
  • If you use it, the compiler will give an error if you try to add more than one abstract method.
  • It helps make your code clear and safe, especially when using lambda expressions.

Example:

@FunctionalInterface
interface Calculator {
    int add(int a, int b);
    
    // You can have default or static methods too
    default void show() {
        System.out.println("Functional Interface Example");
    }
}

What Happens If You Break the Rule?

If you add another abstract method:

@FunctionalInterface
interface Calculator {
    int add(int a, int b);
    int subtract(int a, int b); // Error! More than one abstract method
}

You’ll get a compile-time error because the interface is no longer functional.

Another Example of a Functional Interface

@FunctionalInterface
interface Calculator {
    int operate(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        Calculator add = (a, b) -> a + b;
        System.out.println("Sum: " + add.operate(5, 3));
    }
}

Output:

Sum: 8

Here, the Calculator interface is a functional interface because it has only one abstract method operate(). We implement this method using a lambda expression.

Built-in Functional Interfaces in Java 8

Java 8 provides many ready-to-use functional interfaces in the java.util.function package. Some commonly used ones are:

  • Predicate – takes one argument and returns a boolean.
  • Function<T, R> – takes one argument and returns a result.
  • Consumer – takes one argument and returns nothing.
  • Supplier – takes no argument and returns a result.

Functional interfaces form the foundation of Java 8’s functional programming features. They work hand-in-hand with lambda expressions and are heavily used in APIs like Streams. Next, we will learn about built-in functional interfaces.

Leave a Comment