Why Lambda expression use functional interface only

As you know functional programming is supported in JAVA 8 with the help of Lambda expression. The Lambda expression supported the Functional interface. These interfaces also are known as the Single Abstract method(SAM). The Lambda expressions support only those interfaces which have only one abstract method. It provides a body to the abstract method and an assigned as the reference of the interface.

Whenever you are using the lambda expression for the Function interface, the compiler strictly ensures the interface has only one abstract method. If the interface contains more than one abstract method the program shows an error. Because the lambda expression provides a body to only a single abstract method. When you write lambda expression the compiler assumes the statements of lambda expression will be the body of the abstract method.

public interface Display 
{
	public void show();
}
public class ExampleWithLambda
{
	public static void main(String[] args) 
	{
		Display display = () -> {
			System.out.println("In Show interface we have only Single abstract method");
			System.out.println("This is the body of abstract method");
		};
		display.show();
	}
}

Output: In Show interface we have only Single abstract method
This is the body of abstract method

So, let’s add another abstract method to the interface and try to implement it with Lambda expression.

public interface Display 
{
	public void show();
	public void data();
}
public class ExampleWithLambda
{
	public static void main(String[] args) 
	{
		Display display = () -> {
			System.out.println("In Show interface we have only Single abstract method");
			System.out.println("This is the body of abstract method");
		};
		display.show();
	}
}

Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem: The target type of this expression must be a functional interface at java_8.ExampleWithLambda.main(ExampleWithLambda.java:7)

It breaks at the compile time when you try to refer to the interface. To stop these things, you could add an annotation FunctionalInterface explicitly.

Hence, enhance your knowledge about Lambda expression using the functional interface.

1 thought on “Why Lambda expression use functional interface only”

Leave a Comment