Basic Constructor Reference Syntax
You'll learn how to reference a class constructor using the compact ClassName::new syntax.
In the previous lesson, you saw that constructor references exist as a special form of method reference. Now let's look at the exact syntax and how it works.
The ClassName::new Syntax
Just as you can reference static methods with ClassName::methodName and instance methods with objectReference::methodName, you can reference a constructor with:
ClassName::new
This syntax creates a reference to the constructor of that class. Java automatically infers which constructor to use based on the target functional interface.
How It Works
When you write String::new, you're not calling the constructor immediately. Instead, you're creating a reference that can be used to call the constructor later. Think of it like handing someone a phone number instead of making the call yourself—they can dial it when needed.
The functional interface's abstract method signature determines which constructor gets referenced. If the functional interface takes no parameters, Java uses the no-arg constructor. If it takes one parameter, Java uses a single-parameter constructor, and so on.
Example with Supplier
Supplier<String> stringSupplier = String::new;
String emptyString = stringSupplier.get(); // Creates new String()
Here, String::new references the no-argument constructor because Supplier has a zero-parameter get() method.
Example with Function
Function<String, String> stringCopier = String::new;
String copy = stringCopier.apply("Hello"); // Creates new String("Hello")
This references the String(String) constructor because Function passes one argument.
Key Takeaway: The ClassName::new syntax creates a constructor reference that matches the parameter signature of the target functional interface's abstract method.