0Pricing
Java Academy · Lesson

Constructor References

Use ClassName::new to create instances via functional interfaces like Supplier and Function.

Constructor References is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Two-Arg Constructor as BiFunction

Constructors with two parameters match BiFunction<T,U,R>:

record Point(int x, int y) {}

BiFunction<Integer, Integer, Point> makePoint = Point::new;
Point p = makePoint.apply(3, 4);
System.out.println(p); // Point[x=3, y=4]

Constructor Reference in Stream.map

Convert strings to objects using a constructor reference:

import java.util.*;
import java.util.stream.*;

List<String> names = List.of("Alice","Bob","Carol");

List<Person> people = names.stream()
    .map(Person::new)  // calls new Person(name) for each
    .collect(Collectors.toList());

people.forEach(System.out::println);
// Person(Alice)
// Person(Bob)
// Person(Carol)

Array Constructor Reference

Create arrays dynamically with Type[]::new. This is used by Stream.toArray():

import java.util.stream.*;

String[] arr = Stream.of("a","b","c")
    .toArray(String[]::new);

for (String s : arr) System.out.print(s + " ");
// a b c

int[] sizes = {3, 5, 2};
String[][] matrix = Arrays.stream(sizes)
    .mapToObj(String[]::new)
    .toArray(String[][]::new);

Factory Interface Pattern

Define a custom functional interface for factories, then use constructor references:

@FunctionalInterface
interface Factory<T> {
    T create(String config);
}

class DBConnection {
    String url;
    DBConnection(String url) { this.url = url; }
    public String toString() { return "DB(" + url + ")"; }
}

Factory<DBConnection> dbFactory = DBConnection::new;
DBConnection conn = dbFactory.create("jdbc:postgresql://localhost/mydb");
System.out.println(conn);

Dependency Injection with Constructor References

Frameworks often use functional factories for lazy instantiation. Constructor references make this pattern clean:

import java.util.function.*;

class ServiceLocator {
    private final Map<String, Supplier<?>> registry = new HashMap<>();
    
    <T> void register(String name, Supplier<T> factory) {
        registry.put(name, factory);
    }
    
    @SuppressWarnings("unchecked")
    <T> T get(String name) { return (T) registry.get(name).get(); }
}

ServiceLocator loc = new ServiceLocator();
loc.register("counter", Counter::new);
Counter c = loc.get("counter");

Choosing Between Lambda and Constructor Reference

Use a constructor reference when the lambda body is just new Type(args):

// Lambda:
Function<String, Person> f1 = name -> new Person(name);

// Constructor reference (preferred):
Function<String, Person> f2 = Person::new;

// When you need extra logic, stick with lambda:
Function<String, Person> f3 = name -> new Person(name.trim().toLowerCase());

Generic Types and Constructor References

Generic classes work too — the type is inferred from the functional interface context:

import java.util.*;
import java.util.function.*;

// ArrayList::new matches Supplier<ArrayList<String>>
Supplier<List<String>> listFactory = ArrayList::new;
List<String> l1 = listFactory.get();
List<String> l2 = listFactory.get(); // independent lists
l1.add("hello");
System.out.println(l2.size()); // 0

Stream Collectors using Constructor References

Use constructor references in collectors to build custom result containers:

import java.util.stream.*;

// Collect into a LinkedList using a constructor reference supplier
LinkedList<String> linked = Stream.of("a","b","c")
    .collect(Collectors.toCollection(LinkedList::new));
System.out.println(linked.getFirst()); // a

Primitives and Autoboxing

Constructor references for wrapper types handle autoboxing:

// Integer::new is deprecated in Java 9+, but illustrates the concept
// Use Integer.valueOf or just autoboxing in modern Java
Function<String, Integer> intParser = Integer::parseInt; // static method ref
System.out.println(intParser.apply("42")); // 42

Quick Check

What functional interface does a no-argument constructor reference like ArrayList::new match?

Recap: Constructor References

Key takeaways:

  • Syntax: ClassName::new — delegates to the matching constructor
  • No-arg → Supplier<T>; one-arg → Function<T,R>; two-arg → BiFunction
  • Array constructor: Type[]::new — used with Stream.toArray()
  • Cleaner than lambda when the lambda body is just 'new Type(args)'
  • Use Collectors.toCollection(LinkedList::new) for typed collection results

Frequently asked questions

Is the “Constructor References” lesson free?

Yes — the full text of “Constructor References” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Constructor References”?

Use ClassName::new to create instances via functional interfaces like Supplier and Function. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Constructor References” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Static Method References
  2. Instance Method References on a Specific Instance
  3. Arbitrary-Instance Method References
  4. Constructor References
← Back to Java Academy