#
Method & Constructor references in Java
This tutorial explains to you what is and how to use the method and constructor references in Java.
Before Java 8 this feature wasn't available.
Before reading this tutorial you must be able to understand what a functional interface and a lambda expression is in Java.
In order to implement a functional interface, you can use a method which already exists. This method could be a method of an instance, a static method or a constructor.
Please take a look at the following example and read carefully the comments. The code is self-explanatory.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
From the base application downloaded from Spring Initializr, I updated the main class and added the following classes/interface as below:
package com.example.demo;
public interface MyInterface {
// Abstract method
void sayHelloFromInterface(String helloMessage);
}
package com.example.demo;
public class SayHello {
public void sayHello(String helloMessage) {
System.out.println("Hello "+ helloMessage+ ", from the ABSTRACT method implementation");
}
public static void sayHelloStatic(String helloMessage) {
System.out.println("Hello "+ helloMessage+ ", from the STATIC method implementation");
}
//Constructor
public SayHello(String helloMessage) {
System.out.println("Hello "+ helloMessage+ ", from the Constructor");
}
public SayHello() {
}
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
// Typical lambda usage
MyInterface obj1 = (x) -> System.out.println("Hello "+ x + ", from Lambda");
obj1.sayHelloFromInterface("Dan");
//A SayHello instance must be created to reference an instance method
SayHello sayHello = new SayHello();
// The same thing could be done using an instance reference method
// Instead defining the abstract method in the code directly (using lambda),
// we pass a reference to a method with the same signature
MyInterface obj2 = sayHello::sayHello;
obj2.sayHelloFromInterface("Lily");
// Using the static method reference
MyInterface obj3 = SayHello::sayHelloStatic;
obj3.sayHelloFromInterface("Billy");
// Using the Constructor method reference
MyInterface obj4 = SayHello::new;
obj4.sayHelloFromInterface("Emily");
}
}
When you run, you will get the following result :
Hello Dan, from Lambda
Hello Lily, from the ABSTRACT method implementation
Hello Billy, from the STATIC method implementation
Hello Emily, from the Constructor
Process finished with exit code 0
As you can observe, the SayHello
class is not implementing any interface.