Records were introduced in Java for situation in which you need to store a set of data. That data is always final and cannot be changed. A record can be easily written when you don’t want to design an entire class. Afterward you can use these instances to run your program.
A specific purpose is temporarily storing data from a csv file, with the goal of storing it in another format. Certainly when no additional methods are needed for that data.
Note: Records are always Serialisable , but you cannot influence the way in which they store their data.
public record Employee(String id, String firstName, String lastName, String email, int age) { }
This declaration provides you with an object what can be instantiated with the listed parameters:
Employee e = new Employee("fbo11", "Frederik", "Bonte", "f.bonte@saxion.nl", 52);
e.id();
e.firstName();
e.lastName();
Records are bound to certain rules, so there are limits to what you can and cannot do.
Yes, you may add checks that limit the provided arguments for instance: You don’t even need to write out all the constructor arguments.
record Rectangle(double length, double width) {
public Rectangle {
if (length <= 0 || width <= 0) {
throw new java.lang.IllegalArgumentException(
String.format("Invalid dimensions: %f, %f", length, width));
}
}
}
(From docs.oracle.com)
You may also overload the constructor, so that you need to provide fewer arguments:
record Rectangle(double length, double width) {
public Rectangle(double size) {
this(size, size);
}
}
Yes, this is allowed, but if you are going to write a lot of these, why not simply use a class?
record Rectangle(double length, double width) {
public double surface() {
return length()*width();
}
}
In the example the static variable is also final but that is not required!
If you need your record to provide a main function, then that is allowed.
public record SomeData(int x, int y, Color color) {
// Please note: final is optional here.
public static final Color DEFAULT_COLOR = Color.RED;
public SomeData(int x, int y) {
this(x,y,DEFAULT_COLOR);
}
public static void main(String[] args) {
// This is legal :)
}
}
Just like the stored data, the record class is final. That means cannot create a new class that extends from a record.
Records save time on designing classes. If you only need to store data, a record will do just fine. However, the moreadditions you make to your record, the less sense it makes to have chosen a record.