What are functional interfaces used for in Java 8?

Madhusudan picture Madhusudan · Apr 27, 2016 · Viewed 110.1k times · Source

I came across a new term in Java 8: "functional interface". I could only find one use of it while working with lambda expressions.

Java 8 provides some built-in functional interfaces and if we want to define any functional interface then we can make use of the @FunctionalInterface annotation. It will allow us to declare only a single method in the interface.

For example:

@FunctionalInterface
interface MathOperation {
    int operation(int a, int b);
}

How useful it is in Java 8 other than just working with lambda expressions?

(The question here is different from the one I asked. It is asking why we need functional interfaces while working with lambda expressions. My question is: What are the other uses of functional interfaces besides use with lambda expressions?)

Answer

Sergii Bishyr picture Sergii Bishyr · Apr 27, 2016

@FunctionalInterface annotation is useful for compilation time checking of your code. You cannot have more than one method besides static, default and abstract methods that override methods in Object in your @FunctionalInterface or any other interface used as a functional interface.

But you can use lambdas without this annotation as well as you can override methods without @Override annotation.

From docs

a functional interface has exactly one abstract method. Since default methods have an implementation, they are not abstract. If an interface declares an abstract method overriding one of the public methods of java.lang.Object, that also does not count toward the interface's abstract method count since any implementation of the interface will have an implementation from java.lang.Object or elsewhere

This can be used in lambda expression:

public interface Foo {
  public void doSomething();
}

This cannot be used in lambda expression:

public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}

But this will give compilation error:

@FunctionalInterface
public interface Foo {
  public void doSomething();
  public void doSomethingElse();
}

Invalid '@FunctionalInterface' annotation; Foo is not a functional interface