Java Records (JEP 384)
Java 16 introduced records, which are a new kind of class that can be used to define immutable data classes. Records provide a concise and easy-to-use syntax for creating classes that hold a fixed number of fields.
Here is an example of how to define a record in Java:
record Point(int x, int y) {}
Point p = new Point(1, 2);
int x = p.x();
int y = p.y();
In this example, we are defining a record called Point
that has two fields: x
and y
. The record is defined using the record
keyword, followed by the name of the record and a list of fields in parentheses. To create an instance of the record, we use the new
operator and pass the values for the fields in the order they are defined. To access the fields of the record, we can use the accessor methods that are generated automatically by the compiler.
Records are intended to be used as lightweight alternatives to traditional data classes, and they offer several benefits over traditional classes:
- They are more concise and easier to read and write.
- They are immutable by default, which makes them easier to reason about and safer to use in concurrent environments.
- They provide built-in support for equality, toString, and hashCode methods, which reduces the amount of boilerplate code you need to write.
You can use records in a variety of contexts, such as in method parameters and return types, field declarations, and local variables. However, there are some limitations to what you can do with records, such as not being able to define constructors or instance methods, or to extend other classes or implement interfaces.