Any interface with a SAM (Single Abstract Method) is a functional interface.

JDK is also using functional interface, i.e. java.lang.Runnable, java.util.Comparator, java.util.concurrent.Callable, java.awt.event.ActionListener etc. It can also be created by Java developers.

JDK Functional Interface

@FunctionalInterface is used to annotate functional interface.

@FunctionalInterface annotation is useful for compilation time checking of your code.

SAM(Single Abstract Method) is used by creating Anonymous Inner classes using these interfaces. For example:

Above same concept is used by Functional interfaces. @FunctionalInterface annotation is useful for compile time checking of your code.

Let’s look at example of functional interface:

The interface can also declare the abstract methods from the java.lang.Object class, but still the interface can be called as a Functional Interface:

Once you add another abstract method, i.e. void abstractMethod2() to the interface then the compiler will throw an error.

You cannot have more than one method besides static, default and abstract methods that override methods in java.lang.Object in your @FunctionalInterface or any other interface used as a functional interface.

Key Points
  1. Only one abstract method is allowed in any functional interface. More than one abstract method is not allowed by the compiler. If we remove @FunctionalInterface then we are allowed to add another abstract method, but it will be the non functional interface.
  2. A functional interface is valid even if the @FunctionalInterface annotation would be omitted. It is only for informing the compiler to enforce single abstract method inside interface.

Leave a Reply

Your email address will not be published. Required fields are marked *