Normal Non-Canonical Record Constructors – Object-Oriented Programming

Normal Non-Canonical Record Constructors

A record class declaration can specify any number of non-canonical record constructors—that is, constructors whose signature is not the same as that of the canonical constructor.

In Example 5.30, a non-canonical constructor for the record class CD is implemented at (5). It is a zero-argument non-canonical record constructor to create a record with default values for the component fields.

The first statement in the non-canonical constructor at (6) is an explicit invocation of the canonical constructor with the this() expression. The signature of the this() expression matches that of the canonical constructor in type and in order. The rule is that chaining of constructors with the this() expression (p. 209) must ultimately lead to the canonical constructor being invoked so that all component fields are initialized. In Example 5.30, the constructor invocation at (6) leads to the compact constructor being invoked, and whose execution in turn leads to the implicit canonical record constructor being invoked. Use of this non-canonical constructor is illustrated in the following print statement:

Click here to view code image


System.out.println(new CD());        // Calls the non-canonical constructor

Output from the print statement shows that the record was created after the string values were sanitized:

Click here to view code image

CD[artist=Anonymous, title=No title, noOfTracks=0, year=2022, genre=OTHER]

Non-canonical constructors are primarily used for creating specialized records.

The restrictions noted for the normal and the compact canonical constructors do not apply to a non-canonical constructor: It can be less accessible than its record class, be generic, and can specify a throws clause, but it must invoke another record constructor with the this() expression.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *