Course contentsShow
← Java
Lesson 863 of 2,87021. Generics FundamentalsFree lesson

Generic Constructors and Constructor Invocations

Understand how type arguments apply when calling constructors of generic classes.

Generic Constructors and Constructor Invocations

What you'll learn: How to apply type arguments when creating instances of generic classes through constructor calls.

The Core Idea

When you instantiate a generic class, you're not just calling a constructor—you're also specifying what concrete types should replace the type parameters. This happens at the point of object creation, binding the generic type to a specific type for that instance's lifetime.

How Constructor Invocations Work with Generics

You've already seen that generic classes use type parameters like T or E. When you create an object, you provide type arguments (actual types) either explicitly or through inference:

// Explicit type argument
Box<String> box1 = new Box<String>();

// Diamond operator: type inferred from left side
Box<String> box2 = new Box<>();

// Multiple type parameters
Pair<Integer, String> pair = new Pair<>(42, "answer");

The constructor itself can use the class's type parameters just like any other method or field. When you call new Box<String>(), every occurrence of T inside that Box instance becomes String.

Constructor Body with Type Parameters

Inside a generic class's constructor, you can use type parameters freely:

public class Container<T> {
    private T item;
    
    public Container(T item) {
        this.item = item;  // T is whatever type you specified
    }
}

Container<Double> nums = new Container<>(3.14);  // T = Double here

The constructor parameter type T becomes Double for this specific invocation.

Key Takeaway: When invoking a generic constructor, you bind type arguments to type parameters at creation time, making the constructor's type parameters concrete for that instance—either explicitly with angle brackets or implicitly through the diamond operator.