サイトへ戻る

 â˜•What is the canonical constructor of a Java record?

 

· java

In Java, a record is a new type 🆕 of class that was introduced in Java 16. A record is a concise way to declare a class that is primarily used to store data 💾, similar to a struct in other programming languages.

When you define a record class in Java, the compiler automatically ⚙️ generates a canonical constructor for the record. The canonical constructor is a constructor that takes all the record's components as parameters and assigns them to the corresponding instance variables.

For example, suppose you have a record class called Person with two components, name, and age. The canonical constructor for this record would look like this:

𝒑𝒖𝒃𝒍𝒊𝒄 𝑷𝒆𝒓𝒔𝒐𝒏(𝑺𝒕𝒓𝒊𝒏𝒈 𝒏𝒂𝒎𝒆, 𝒊𝒏𝒕 𝒂𝒈𝒆) {

𝒕𝒉𝒊𝒔.𝒏𝒂𝒎𝒆 = 𝒏𝒂𝒎𝒆;
𝒕𝒉𝒊𝒔.𝒂𝒈𝒆 = 𝒂𝒈𝒆;

}

💡 Note that the canonical constructor is automatically generated by the Java compiler, so you do not need to explicitly define it in your code.

#java #record #canonicalConstructorExplained #programming