Search code examples
javalambdafunctional-interface

Why we do need to write "implements InterfaceName" while implementing a Functional Interface?


Why we do need to write "implements FI" while implementing a FunctionalInterface?

@FunctionalInterface
interface FI
{
 void sayHello(String name);    
}

public class Hello implements FI
{   
  public static void main(String[] args)
  {
    // TODO Auto-generated method stub
    FI fi = (name) -> System.out.println("Hello " + name);
    fi.sayHello("world");
  } 
}

Solution

  • The @FunctionalInterface is just a way to enforce a check from the compiler so that the annotated interface only has one abstract method, nothing more.

    In addition it's clearly stated that

    However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.

    So it's not even required to annotate it explicitly.

    The annotated interface is still an interface and it's used as all other interfaces in Java code so you need to specifically specify when you are implementing it.

    But being a functional interface allows you to define a lambda which overrides it directly:

    FI fi = name -> System.out.println(name);