Interfaces for Custom Functions in Java


Create a Java program to demonstrate the use of an interface for custom function

  • CustomFunction is a functional interface with a single abstract method apply(T t).
  • The Function interface from the java.util.function package is also used, which has a similar method apply(T t).
  • An instance of Function<Integer, String> named toString is created using a method reference Object::toString. This function converts an Integer to a String.
  • An instance of CustomFunction<Integer, String> named customToString is created using the same method reference Object::toString.
  • Both toString and customToString are then used to convert the integer 42 to a string.
  • The results are printed, showing the usage of both Function and CustomFunction interfaces to achieve the same functionality.

Source Code

import java.util.function.Function;
 
@FunctionalInterface
interface CustomFunction<T, R>
{
	R apply(T t);
}
 
public class Main
{
	public static void main(String[] args)
	{
		Function<Integer, String> toString = Object::toString;
		CustomFunction<Integer, String> customToString = Object::toString;
 
		String result1 = toString.apply(42);
		String result2 = customToString.apply(42);
 
		System.out.println("Result using Function : " + result1);
		System.out.println("Result using CustomFunction : " + result2);
	}
}

Output

Result using Function : 42
Result using CustomFunction : 42

Example Programs