Explore Lambda expression in Java 8 with functional Interface

Sun, Nov 17, 2019

Read in 2 minutes

We can say lambda expression a method block without a name and it is useful in implementing the abstract method in the functional interface.

Functional Interface :

Functional interface can have only one abstract method, and it can have any number of default methods .E.g. : Runnable interface.

Before Java 8 :

Before java 8, the interfaces can have only one abstract method and the access modifiers should be public. But after the release of Java 8, interfaces can have default methods also.

Why default methods introduced in interfaces ?

Basically this functional interfaces introduced to acquire backward compatibility. In any old interfaces (like httprequest , comparator) interface if any method needs to be added, all the classes which are implementing that interface have to provide the implementation for that method. To overcome this problem, the Java 8 version, the introduced interfaces can have default methods.

Private methods in interfaces

In java 9, they introduced a new version of interface which contains static methods and private methods also. Static methods are like utility methods that are used inside the interface methods.

Lambda Expression

It contains 3 parts :

public interface FuctionalDemo {
         void calcTax(int salary);
	default int addFunc(int a ,int b) {
		int c=a+b;
		return c;
	}
}
public class LamdaDemo {
	public static void main(String[] args) {
		FuctionalDemo obj= (int a)-> {
			long tax =(long) (a*30/100);
			System.out.println("tax calculated== "+tax);
			};
		obj.calcTax(1000);
	}
}