Java / Java Record Keyword
A record in Java is a special type of class designed to concisely model data. Introduced in Java 16, records automatically generate essential methods, reducing boilerplate code. Here's how to define and use them:
Defining a Record:
Records are declared using the record keyword, followed by the record name and component list within parentheses.
record Person(String name, int age) {}
This creates a Person record with two components: name (String) and age (int).
Records are implicitly final and cannot be abstract.
Components are implicitly final and private.
Records cannot extend other classes, but they can implement interfaces.
A record class can't declare instance fields other than the components.
A record class is not allowed to declare native methods.
Records are immutable data classes that require only the type and name of fields. So ,the main difference between class and record type in Java is that a record has the main purpose of storing data, while a class defines responsibility. Records are immutable, while classes are not.
private, final field for each piece of data.
getter for each field.
public constructor with a corresponding argument for each field.
equals method that returns true for objects of the same class when all fields match.
hashCode method that returns the same value when all fields match.
toString method that includes the name of the class and the name of each field and its corresponding value.