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

56 views Asked by At

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");
  } 
}
2

There are 2 answers

0
Jack On BEST ANSWER

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);
0
Yuri Schimke On

You don't

interface FI {
  void sayHello(String name);
}

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

Hello isn't used as a Functional Interface, and also @FunctionalInterface just makes the compiler enforce the single method contract.