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

Generic Constructors

Understand how constructors can have their own type parameters independent of the class's type parameters.

Generic Constructors

What you'll learn: How constructors can declare their own type parameters that are separate from the class's type parameters.

The Core Idea

Just like methods can have their own type parameters (as you've learned), constructors can too. A generic constructor declares its own type parameter list independent of any type parameters the class itself might have. This means:

  • A generic class can have a generic constructor with different type parameters
  • A non-generic class can have a generic constructor with its own type parameters
  • The constructor's type parameter scope is limited to that constructor only

Think of it this way: if a class's type parameters are like family traits everyone inherits, a constructor's type parameters are like temporary tools used only during the "building" phase—they disappear once the object is constructed.

Syntax

The type parameter list appears before the constructor name:

public class Container<T> {
    private T value;
    
    // Generic constructor with its OWN type parameter U
    public <U> Container(U input) {
        // U is available here, independent of T
        System.out.println("Constructing with type: " + input.getClass().getName());
        // Could convert U to T, or ignore U entirely
    }
}

Notice <U> appears right before Container. That U is not the same as the class's T.

When Is This Useful?

Generic constructors shine when you need to accept input of a different type than what the class stores, often for conversion or initialization logic that's more flexible than the class's main type.

Key Takeaway: Constructors can declare their own type parameters using <TypeParam> before the constructor name, giving you flexibility independent of the class's type parameters.