Constructor Reference in Java

What is a Constructor Reference in Java?

Introduced as part of Java 8, Constructor Reference is a concept that can only be utilized within the context of Functional Interfaces. This technique enables us to reference pre-defined constructors and assign them to the desired type of Functional Interface without actually instantiating the class. In essence, Constructor Reference allows us to refer to constructors in a way that avoids instantiation.

Syntax

java constructor reference

Example 1:

@FunctionalInterface
interface MyInterface {
  Message send(String message);
}

class Message {

  public Message(String message) {
    System.out.println(message);
  }
}

class Test {

  public static void main(String[] args) {
    MyInterface myInterface = Message::new;
    myInterface.send("Hello!");
  }
}

Output: Hello!

Here, we passed the string Hello! as a parameter to the send() function, and that parameter gets forwarded to the constructor, which accepts the string as a parameter.

Example 2:

Let’s update the class Message by adding two more constructors:

class Message {

  public Message(String message) {
    System.out.println(message);
  }

  public Message(String message1, String message2) {
    System.out.println(message1 + message2);
  }

  public Message(String message1, String message2, String message3) {
    System.out.println(message1 + message2 + message3);
  }
}

Now, to refer to the constructor that accepts two parameters with Constructor Reference, we need to define the corresponding method inside the Functional interface.

@FunctionalInterface
interface MyInterface {
  Message send(String message1, String message2);
}

Let’s implement the main method and execute the program:

class Test {

  public static void main(String[] args) {
    MyInterface myInterface = Message::new;
    myInterface.send("Hello ", "World!");
  }
}

Output: Hello World!

We called the send() method that accepts two parameters, and the corresponding constructor got invoked.

I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *