November 26, 2018

What are functional interfaces in java – understanding the use of functional interface in java

As far as my own understanding goes for functional interfaces, they are used for identifying Java interfaces, which has only one abstract method. A functional interface can have more than one method in it, but you have to provide default implementation for all the methods except one.

For example, the Runnable  interface is a functional interface. It has only one abstract method in it, i.e run() .

Functional interfaces are generally marked with @FunctionalInterface annotation, it is not necessary to use this annotation. But it helps compiler to know that, this interface is supposed to have only one abstract method. And will make sure that, your interface has only one abstract method.

That’s it. That’s all about Functional Interface.

Let’s write some code.

Case 1 :

An Interface that is marked with @FunctionalInterfacebut doesn’t declare any method. It means this interface is empty.

@FunctionalInterface
public interface FunctionalInterfaceTest {
}

The above code will give a compile time error. As, you haven’t declared any method and this interface is marked with @FunctionalInterface annotation.

Case 2 :-

An interface, which is marked with @FunctionalInterfaceand has exactly one abstract method

@FunctionalInterface
public interface FunctionalInterfaceTest {
    void abstractMethod();
}

This compiles without any issue.

Case 3  :-

An interface annotated with @FunctionalInterfacebut has more than one abstract method.

@FunctionalInterface
public interface FunctionalInterfaceTest {
    void abstractMethod();
    void abstractMethod_2();
}

You will get Compile time error.

Case 4 :-

An interface annotated with @FunctionalInterface , having more than one method but only one of them is abstract

@FunctionalInterface
public interface FunctionalInterfaceTest {
    void abstractMethod();
    default void abstractMethod_2() {
        //Has Empty Implementation - Empty Body
    };
}

I have provided an empty implementation for abstractMethod_2 ,and now, it compiles without any issue.

Compiler Time Error :-

An interface is marked with @FunctionalInterface , but has more than one or zero abstract method in it. Compiler will throw following error.

java: Unexpected @FunctionalInterface annotation
  FunctionalInterfaceTest is not a functional interface
    multiple non-overriding abstract methods found in interface FunctionalInterfaceTest

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *