Java 8 – Referencing Constructor Using Lambda & Double Colon Operator1 min read

Java

Overview

With the introduction of Lambda and double colon operator in Java 8, a lot really changed, one of the changes can be seen in the way the Constructors can be referenced.

1. Referencing Constructor in Java 8

It can be done in two ways in Java 8:

  • Using Double Colon Operator(::)
  • Using Lambda Expression(->)

1.1. Using Double Colon Operator(::)

At last, it’s possible to reference a constructor of a class. We can do this by mentioning the double colon(::) keyword, for example:

ClassName :: new

To do this, first we define a functional interface named Factory with just one method i.e. demo(), whose definition resembles with that of a String class constructor:

@functionalInterface
interface Factory{
    public String demo(String original);
}

Now, using demo() method signature, we can call String class constructor that takes in String as an input parameter, after applying double colon operator it will look like:

public static void main(String[] args) {
     Factory fc = String::new;
     System.out.println(fc.demo("Hello"));
}
output:Hello

Please note, Factory here denotes our functional interfacefollowed by fc, a reference variable. Up next on the RHS is the String class whose signature matches with the interface’s method demo() signature and finally we have the double colon operator(::) followed by a new keyword, which means that a String constructor is invoked here.

1.2 Using Lambda expression(->)

With Lambda Expression, referencing a constructor is much more understandable, i.e. above expression Factory fc = String :: new; looks like below in Lambda expression.

Factory factory = Str -> new String(Str);

*Str is the parameter being passed to String constructor.

Conclusion

In this mini-article, we learned how to:

  • Reference a class constructor using Lambda.
  • Use a double colon operator to do the same operation.

As usual, you can find the code on Github

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.