Constructor References
Use ClassName::new to create instances via functional interfaces like Supplier and Function.
What Are Constructor References?
A constructor reference uses ClassName::new to create objects via a functional interface. The functional interface's parameters match the constructor's parameters.
import java.util.function.*;
class Person {
String name;
Person(String name) { this.name = name; }
public String toString() { return "Person(" + name + ")"; }
}
// Function<String, Person> — calls Person(String)
Function<String, Person> factory = Person::new;
Person p = factory.apply("Alice");
System.out.println(p); // Person(Alice)No-Arg Constructor as Supplier
A no-arg constructor matches Supplier<T>:
class Counter {
int count = 0;
void inc() { count++; }
}
Supplier<Counter> newCounter = Counter::new;
Counter c1 = newCounter.get();
Counter c2 = newCounter.get(); // independent instances
c1.inc();
System.out.println(c1.count); // 1
System.out.println(c2.count); // 0