Java8 - Functional interfaces

Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:23:32 Viewed : 239


A functional interface in Java is an interface that has exactly one abstract method (SAM) or single abstract method. Functional interfaces play a crucial role in the world of lambda expressions and provide a foundation for expressing instances of single-method interfaces concisely using lambda syntax.

In Java, functional interfaces are annotated with the @FunctionalInterface annotation. While the annotation is optional, using it helps the compiler enforce the design intent of having only one abstract method. If a functional interface has more than one abstract method, the compiler will raise an error.

Here is an example of a simple functional interface:

java
@FunctionalInterface interface MyFunctionalInterface { void myMethod(); }

This interface has a single abstract method, myMethod(). Since it is annotated with @FunctionalInterface, the compiler will ensure that no other abstract methods are added.

Functional interfaces can also have default methods, static methods, and abstract methods from the java.lang.Object class (such as equals(), hashCode(), and toString()). However, the presence of more than one abstract method will violate the functional interface contract.

Here is an example with a functional interface that includes a default method:

java
@FunctionalInterface interface Calculator { int calculate(int x, int y); default double sqrt(int x) { return Math.sqrt(x); } }

The Calculator interface has one abstract method, calculate(), and a default method, sqrt(). This is still a functional interface because there is only one abstract method.

Functional interfaces are essential in Java 8 and later versions because they provide a way to use lambda expressions and method references effectively. When you create a lambda expression or use a method reference, you are essentially providing an implementation for the single abstract method of a functional interface. This allows for more expressive and concise code, especially when working with APIs like the Stream API, which heavily relies on functional interfaces.

Search
Related Articles

Leave a Comment: