Skip to main content
A generic constructor is a constructor that declares its own formal type parameters, distinct from any type parameters declared by the enclosing class. This allows the constructor to enforce type constraints and perform type inference specifically for the instantiation process, regardless of whether the enclosing class itself is generic or non-generic.

Syntax

The type parameter section, enclosed in angle brackets (<>), must precede the constructor’s name.

Core Mechanics

1. Independence from Class Generics

A generic constructor’s type parameters are scoped strictly to the constructor. If the enclosing class is also generic, the constructor can declare type parameters that are entirely independent of the class-level type parameters.

2. Type Inference

When a generic constructor is invoked, the Java compiler typically infers the type arguments based on the actual arguments passed to the constructor.

3. Explicit Type Witness

If the compiler cannot infer the type, or if you need to enforce a specific type hierarchy, you can provide an explicit type witness. The type witness is placed in angle brackets immediately before the class name in the new expression.

Bounded Type Parameters in Constructors

Generic constructors support bounded type parameters using the extends keyword to restrict the types that can be passed during instantiation. Multiple bounds can be specified using the & operator.

Interaction with the Diamond Operator

When instantiating a generic class that also has a generic constructor, the syntax must accommodate both the class type arguments and the constructor type arguments. If you use an explicit type witness for the constructor, you cannot use the diamond operator (<>) for the class type parameters; both must be explicitly declared.
Tired of Poor Java Skills? Fix That With Deep Grasping!Learn More