Rushikesh Rushikesh -4 years ago 170
Java Question

What is use of Functional Interface in Java 8?

I came across new term named "Functional Interface" in Java 8.

I could found only one use of this interface while working with Lambda expressions.

Java 8 provides some inbuilt functional interfaces and if we want to define any functional interface then we can make use of @FunctionalInterface annotation. It will allow to declare only 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 while working with Lambda expressions)?

The question here is different than the one I asked. It is asking why we need Functional Interface while working with Lambda expression. My question is use of Functional interface other than with Lambda expression.

Answer Source

@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

NOTE: You can not use lambdas in @FunctionalInterface with generic method:

@FunctionalInterface
public interface Foo {
    <T> void doSomething(T t);
}

This statement won't:

Foo foo = (Object obj) -> obj.equals(anyObj);

With error:

Target method is generic

However you can use it with method reference:

Foo foo = Object::equals;

You can read about it in specs.

This does not refer to generic @FunctionalInterface

@FunctionalInterface
public interface Foo<T> {
    void doSomething(T t);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download