89. Introducing the canonical and compact constructors for records
In the previous problem, we created the MelonRecord
Java record and we instantiated it via the following code:
MelonRecord melonr = new MelonRecord("Cantaloupe", 2600);
How is this possible (since we didn’t write any parameterized constructor in MelonRecord
)? The compiler just followed its internal protocol for Java records and created a default constructor based on the components that we provided in the record declaration (in this case, there are two components, type
and weight
).
This constructor is known as the canonical constructor and it is always aligned with the given components. Every record has a canonical constructor that represents the only way to create instances of that record.
But, we can redefine the canonical constructor. Here is an explicit canonical constructor similar to the default one – as you can see, the canonical constructor simply takes all the given...