Monday, August 9, 2021

Java 8: Why functional interface has ONLY ONE ABSTRACT method

As we all know, one of the key features introduced in Java 8 is functional interface. Functional can have as many as default and static methods, but only one abstract method, question is why??

If functional interface overrides one of public abstract methods on java.lang.Object, it will not count in interface's abstract methods as it WILL have implementation in Object class or elsewhere. For example, Comparator is functional interface and it has TWO abstract methods, comapre and equals, out of which equals method signature is matching with Object class' equals method

We know, lambda implementation of functional interface abstract method checks the parameters passed to lambda expression to match it against the parameters of functional interface abstract method. 

For example

() -> System.out.println("Hello World"); // abstract method in functional interface has no arguments

(i) -> System.out.println("Hello "+i); // abstract method in functional interface has ONE argument 

(i, j) -> System.out.println("Sum is "+(i+j)); // abstract method in functional interface has TWO arguments 

If the list of parameters passed is not matching with the arguments, it results in compilation error. If so, question is why Java 8 does not allow 2 or more abstract methods in Functional Interfaces, like shown in below example which will give compilation error saying "The target type of this expression must be a functional interface"




       


package java8.twoabstractmethods;

public class TwoAbstractMethodsDemo {

	public static void main(String[] args) {
		MoreAbstractMethodsDemo demo1 = (x, y) -> System.out.println("Sum is "+(x+y));
		demo1.sum(1, 2);
		
		//MoreAbstractMethodsDemo demo2 = (k) -> System.out.println("Hi "+k);
		//demo2.sayHi("Ganesh");
	}

}
@FunctionalInterface
interface MoreAbstractMethodsDemo{
	void sum(int a, int b);
	//void sayHi(String name);
}

Possible answers to this questions are follows, 

1. Lambda expression is an implementation of the functional interface, hence if there are multiple abstract methods, we would have required to provide implementation for all abstract methods, which would have made code more non-readable

2. With functional interface Java has introduced functional programming like JavaScript where function can be passed as parameters. In order to achieve that, function should have only one behavior

Please add in comments if you know any other answer

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...