Skip to main content

Java Functional Interface

1. What is Functional Interface

An interface with only one abstract method is called Functional Interface.

Pre Java 8, there was no concept of Functional Interface. However, interfaces like Comparator and Runnable have only one abstract method. Hence they fell into the Functional Interface category in Java 8 unintentionally.

2. Example

2.1 getSellingPrice method snippet from App.Java

package org.geekmj.java8;

public class App {

	public static void main(String[] args) {
		// 
	}

	private static float getSellingPrice(float cost, float couponDiscount, DiscounterFunctionalInterface discounter) {
		return cost - couponDiscount - discounter.discount(cost);
	}
}

Here, we have a method getSellingPrice, with three arguments cost, couponDiscount and discounter. discounter is of type DiscounterFunctionalInterface. It calculates the selling price for an item.

2.2 DiscounterFunctionalInterface.java

package org.geekmj.java8;

@FunctionalInterface
public interface DiscounterFunctionalInterface {
	public float discount(float cost);
}

Here, DiscounterFunctionalInterface is a functional interface with one abstract method discount. The implementation of this method will calculate the discount for a given cost applying discount percentage.

2.3 App.java

package org.geekmj.java8;

public class App {

	public static void main(String[] args) {

		/* Discount for Cloth is 10% of cost */

		System.out.println("Selling Price of Cloth Prices 200 after discount is " + getSellingPrice(200f, 0f, cost -> (cost * 10) / 100));

		/* Discount for Book is 5% of cost */

		System.out.println("Selling Price of Book Priced 150 after discount is " + getSellingPrice(150f, 10f, cost -> (cost * 5) / 100));
	}

	private static float getSellingPrice(float cost, float couponDiscount, DiscounterFunctionalInterface discounter) {
		return cost - couponDiscount - discounter.discount(cost);
	}
}

Here, in the main method, you had made a call to getSellingPrice twice. You can see how we passed two different implementations of DiscounterFunctionalInterface using lambda expressions.

getSellingPrice(200f, 0f, cost -> (cost * 10) / 100)
getSellingPrice(150f, 10f, cost -> (cost * 5) / 100)

The compiler map the lambda expression signature with the discount method in DiscounterFunctionalInterface. It happens so because we have only one abstract method in DiscounterFunctionalInterface.

The above sample is also an example of Behaviour Parameterization or Execute Around Pattern using Lambda Expression.

3. Can you have multiple methods in Functional Interface?

Yes, you can have multiple methods in a Functional Interface. However, they can only be default methods.

4. Why it is Required?

Lambda Expression in Java 8 provides the ability to define a concise inline function that we can pass around.

In Java, we can pass Class and Primitive data types as an argument to a method.

Hence Java 8 Designer decided to introduce Functional Interface. Which will have only one abstract method. It allows the concise implementation of a Functional interface using Lambda expression. It further allowing lambda expression to pass around easily to methods.

Functional Interface is a simple design choice to represent Lambda Expression as an instance.

5. Function Descriptor

The description of the signature of the Lambda Expression is the same as the signature of the Functional Interface abstract method. Hence this abstract method is also called Function Descriptor.

6. @FunctionalInterface annotation

Most of the Functional Interfaces in Java 8 are annotated with @FunctionalInterface. However, it is not mandatory. But it is considered a good practice to use @FunctionalInterface.

7. Inbuilt Functional Interfaces in Java

In Java 8, we have several inbuilt Functional Interfaces that can be used by Lambda Expression readily. We will learn about them in another tutorial guide.

8. Source Code

Source code is available on GitHub for clone and download.

Comments

Popular posts from this blog

Useful SFTP terminal commands

First Step - Connect to a remote computer sftp -i ~/.ssh/LightsailDefaultKey-ap-south-1.pem ubuntu@52.66.180.155 Similar to ssh command. Output: Connected to 52.66.180.155. sftp> Remote and Local computer commands When we relay basic terminal commands at sftp> like 'pwd , ls , cd , and it is executed at the remote computer. Basic terminal commands above when prefixed with l like lpwd , lls , lcd and etc. it is executed at a local computer. For e.g. List all files in the present working directory at the remote computer: sftp> ls List all files in the present working directory at the local computer: sftp> lls Sending a local computer file to present the working directory of a remote computer sftp> put /Users/mj/Downloads/test.png Output Uploading /Users/mj/Downloads/test.png to /home/ubuntu/test.png /Users/mj/Downloads/tech-mrit-prod.ovpn 100% 13KB 382.9KB/s 00:00 References How To Use SFTP to Securely Transfer Files with a Re...

Understanding Type Checking

A few examples of types in the context of programming language can be integer, float, character, string, array, etc.  When a program executes then data flow between instructions and values of specific types are assigned to a variable after some operation. It's important for the system to verify if the correct types are used as operands in operations. For e.g. In a sum operation, the expectation for operands to be of numeric type. The program's execution should fail in the case there is inconsistency. We can classify programming languages into two categories based as per their ability to cater to type safety: Dynamically Typed Language Statically Typed Language