DEV Community

Cover image for Java 8 - Functional Interface
Sangharsha Chaulagain
Sangharsha Chaulagain

Posted on

Java 8 - Functional Interface

In the previous post of this series, we discussed what is lambda expression and how can we write lambda expression. In this post, we will discuss how we can execute lambda expression. As I said, at the end of the last post, we can execute lambda expression by using Java 8's new feature, Functional Interface.

So what is Functional Interface?

The interface containing the single abstract method(SAM) are called Functional Interface. Some of the Functional Interface we may know are:

Interface method
Runnable run()
Callable call()
Comparable compareTo()
ActionListener actionPerformed()

In version 1.8, java introduced one annotation @FunctionalInterface to specify interface as functional interface explicitly. But the annotation is optional. However, it is recommended to write the annotation. It helps prevent any additional abstract method. If the interface with annotation consists of more than one abstract method, then we get a compile-time error saying:

error: Unexpected @FunctionalInterface annotation
@FunctionalInterface
^
  CustomInterface is not a functional interface
    multiple non-overriding abstract methods found in interface CustomInterface
Enter fullscreen mode Exit fullscreen mode

Note: Functional interface can have multiple default and static method.

Example 1:

@FunctionalInterface
interface A {
    void m1();
} 

@FunctionalInterface
interface B extends A {
}

@FunctionalInterface
interface C extends A {
    void m1();
}

@FunctionalInterface
interface D extends A {
    void m2();
}
Enter fullscreen mode Exit fullscreen mode

In the above example, the interface D definition is invalid since it contains two methods: m1() [extended from interface A] and m2().

In the next part, I will write about how lambda expression can be used with the functional interface.

Top comments (0)