An immutable class where its purpose is to hold data, the next structure is needed:
fields are private final
the only constructor is public and holds all the setters of the fields
there is no explicit setter method (immutable)
the only methods are the getters, equals(), hashCode() and toString() to all fields
In order to create such a data container, a lot of boilerplate code is needed.
Modifying the data container need other coding since the methods should be updated not just the fields.
From Java 17 the whole class can be replaced with a record structure which ensures that the class is a data container for purpose but no need to maintain the rest of the code.
A record is an immutable class which represents data container for given classes (primitives are included).
This structure is equally usable as a class would be.
The method names of getters of the record are originated from the names of the specific fields.
The toString() method will give different result from the usual.
Fields and methods of the record can be accessed via using this.fieldName and this.methodName().
EXAMPLE FOR A SIMPLE RECORD:
A record can be extended:
overriding its constructor
overloading (adding additional) its constructor
adding additional (static) fields
adding additional (static) methods
The this keyword points to the record itself, the this() method points to the original (automatically generated) constructor.
Overriding the automatically created constructor is valid, however, overriding again with the same method signature is not allowed.
EXAMPLE FOR OVERRIDING THE CONSTRUCTOR OF A RECORD:
EXAMPLE FOR OVERLOADING THE CONSTRUCTOR TO A RECORD:
EXAMPLE FOR ADDING STATIC CONTENT TO A RECORD: