# Method & Constructor references in Java

In 
Published 2022-12-03

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.

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.

From the base application downloaded from Spring Initializr, I updated the main class and added the following classes/interface as below:

MyInterface.java
package com.example.demo;

public interface MyInterface {

    // Abstract method
    void sayHelloFromInterface(String helloMessage);
}
SayHello.java
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() {
    }
}
DemoApplication.java
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