Java functional interface Tutorial

  • Post author:
  • Post category:Java

In this section, we will learn what the functional interface is and how to use it in Java.

What is functional interface?

An interface with just one abstract method is known as a functional interface. The static and default methods are not counted to designate an interface a functional interface. No additional steps, other than what I have already discussed, are needed to declare an interface as functional.

Example: functional interface

public interface FirstInterface {

    private void method1(){
        System.out.println("This message is coming from a private method");
    }
    default void method2(){
        method1();
    }
    void method3();
}

This interface is functional because even though it has one private and one default method, there’s only one abstract method and so it is a functional interface.

Java @FunctionalInterface annotation

You can annotate a functional interface with the @FunctionalInterface annotation. When we apply this annotation to an interface, the compiler will verify the annotated interface to see if it follows the rules of the functional interface. This means the target interface will be controlled to see if it only has one abstract method. If this wasn’t true, the compiler will throw an error and won’t compile.

Basically, when using this annotation on an interface, we’re implicitly telling the compiler what the purpose of the target interface is. Now the compiler will also check the interface and make sure that we wrote the body of that interface in the correct way.

Example: Using @FunctionalInterface annotation

The following is an example of a functional interface annotated with the @FunctionalInterface annotation:

@FunctionalInterface
public interface Runner {
    void run();
}

Another example:

@FunctionalInterface
public interface Runner {
    void run();
    void run2();
}

This interface is not a functional interface because it has two abstract methods in it. Here because we used the `@FunctionalInterface` annotation on top of this interface, if we compile and run a program that has such interface, we will get compile time error with this:

Error:(3, 1) java: Unexpected @FunctionalInterface annotation

tuto.Runner is not a functional interface

multiple non-overriding abstract methods found in interface tuto.Runner

Functional interface and lambda expression

For someone who doesn’t know what Java Lambda is and what is does, there’s pretty much no difference between a functional interface and a normal non-functional interface. Both can be implemented by a class and their abstract methods will be overridden by that class.

But in the Java lambda section we will explain the real use case of functional interface.

Leave a Reply