Java introduced the record class in Java 14 as a new type of class primarily intended to model immutable data. A record class provides a concise way to declare classes whose main purpose is to store data. It automatically generates useful methods such as constructors, accessors, equals(), hashCode(), and toString(), making it ideal for representing simple data aggregates.
Here's a breakdown of the components of a record class:
Keyword
record: It indicates that this is a record class.Record Name: The name of the record class.
Components: The fields or components of the record, declared similarly to fields in a regular class. These components are implicitly final.
Constructor(s): The compiler automatically generates a constructor that initializes the components of the record.
Accessor Methods: Accessor methods for each component are generated by default. These methods are named according to the component names.
equals(),hashCode(), andtoString(): The compiler automatically generatesequals(),hashCode(), andtoString()methods based on the components of the record.
Here's a simple example of a record class representing a Point:
public record Point(int x, int y) { // No need to explicitly define constructor, accessors, equals(), hashCode(), or toString() }
With this declaration:
- You get a constructor
Point(int x, int y)that initializesxandy. - Accessor methods
x()andy()are generated to retrieve the values ofxandy. equals(),hashCode(), andtoString()methods are automatically generated based on thexandycomponents.
You can use this record class as you would use any other class:
public class Main { public static void main(String[] args) { Point p1 = new Point(2, 3); Point p2 = new Point(2, 3); System.out.println(p1.equals(p2)); // Output: true System.out.println(p1.hashCode()); // Output: Same hashCode as p2 System.out.println(p1); // Output: Point[x=2, y=3] } }
No comments:
Post a Comment