Constructor Reference in Java

What is a Constructor Reference in Java?

Constructor Reference is a concept introduced as part of Java 8.

We can only use the Constructor Reference in the context of Functional interfaces.

Using the Constructor Reference we can refer to previously defined constructors and assign them to the desired type of Functional Interface.

Constructor Reference is used to refer to a constructor without instantiating the class.


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.
 
Happy coding!

Leave a Reply

Your email address will not be published.