Introduction to Constructor References
You'll learn: How to use the :: operator to reference constructors as shorthand for creating new objects in functional contexts.
What Are Constructor References?
Just as method references let you point to an existing method instead of writing a lambda, constructor references let you point to a constructor. Instead of writing x -> new Person(x), you can write Person::new. It's a cleaner, more direct way to express object creation when the lambda's only job is to instantiate something.
The Syntax
The pattern is simple:
ClassName::new
This references the constructor of ClassName. Java figures out which constructor based on the context — just like it does with method references.
When to Use Constructor References
Anytime a functional interface expects you to create and return a new object, a constructor reference often fits perfectly.
Example with Function:
// Lambda version
Function<String, StringBuilder> builderMaker = s -> new StringBuilder(s);
// Constructor reference version
Function<String, StringBuilder> builderMaker = StringBuilder::new;
Both do the same thing: take a String and create a StringBuilder from it.
Example with Supplier:
// Lambda version
Supplier<ArrayList<String>> listMaker = () -> new ArrayList<>();
// Constructor reference version
Supplier<ArrayList<String>> listMaker = ArrayList::new;
The no-argument constructor is called each time get() is invoked.
How Java Resolves the Constructor
Java matches the constructor signature to the functional interface's abstract method signature. A Function<String, Person> would call new Person(String), while a BiFunction<String, Integer, Person> would call new Person(String, Integer).
Key Takeaway: Constructor references (ClassName::new) provide a concise way to reference constructors in functional contexts, letting Java match the appropriate constructor based on the target type's method signature.