Constructor References with No Arguments
You'll learn how to use constructor references with Supplier to create new object instances without passing arguments.
When you need to create objects lazily or on-demand, constructor references pair beautifully with the Supplier<T> functional interface. Since Supplier takes no arguments and returns a value, it's the perfect match for no-argument constructors.
The Pattern
A constructor reference for a no-arg constructor looks like this:
ClassName::new
When used as a Supplier, this reference tells Java: "When get() is called, invoke the no-argument constructor and return the new instance."
Basic Example
Supplier<StringBuilder> builderSupplier = StringBuilder::new;
// Each call creates a new StringBuilder
StringBuilder sb1 = builderSupplier.get();
StringBuilder sb2 = builderSupplier.get();
// sb1 and sb2 are distinct objects
This is equivalent to the lambda:
Supplier<StringBuilder> builderSupplier = () -> new StringBuilder();
Why Use This?
Constructor references with Supplier shine when you need:
- Factory patterns: Creating objects on demand
- Lazy initialization: Delaying object creation until needed
- Default value providers: Supplying fresh instances
class User {
public User() { }
}
Supplier<User> userFactory = User::new;
User admin = userFactory.get();
User guest = userFactory.get();
// Two distinct User objects
Key Takeaway: Constructor references with no arguments (ClassName::new) work perfectly with Supplier<T>, providing a clean, readable way to create object factories that produce new instances on demand.