A canonical constructor is the primary constructor of a JavaDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
record whose signature exactly matches the record’s state description (the components declared in the record header). The Java compiler implicitly generates this constructor to initialize the private final fields corresponding to each record component.
When explicitly declared, the canonical constructor must have an access modifier that provides at least as much access as the record class itself, and its parameter list must perfectly mirror the record’s component list in both order and type.
Implicit Canonical Constructor
By default, the compiler automatically generates the canonical constructor. No explicit code is required.Explicit Canonical Constructor
A developer can explicitly declare the canonical constructor to intercept the initialization process. The parameter names and types must strictly match the record components.Compact Canonical Constructor
Java provides a specialized shorthand syntax for the canonical constructor in records, known as the compact constructor. It omits the parameter list entirely. The parameters are implicitly declared, and the definite assignment of the record’s fields occurs automatically at the end of the constructor body.Rules and Constraints
- Signature Matching: The parameter types and order in an explicit canonical constructor must strictly match the record’s state description.
- Visibility: The access modifier cannot be more restrictive than the record itself. For example, if the record is
public, the canonical constructor must bepublic. - Definite Assignment: In a standard explicit canonical constructor, all blank
finalfields corresponding to the record components must be definitely assigned. They can be assigned the result of any valid expression; they are not strictly required to be assigned the exact, unmodified parameter value. In a compact constructor, the compiler handles the assignment automatically. - Control Flow: A compact constructor cannot contain explicit
returnstatements. - Exceptions: The canonical constructor must not declare a
throwsclause at all, regardless of whether the exceptions are checked or unchecked.
Master Java with Deep Grasping Methodology!Learn More





