record keyword in Java
- Details
- Written by Nam Ha Minh
- Last Updated on 30 March 2020   |   Print Email
In Java, the record keyword is used to declare a special class type that acts as a “data carrier” i.e. model class or POJO class. This keyword is added to the Java language since JDK 14.
Consider an example:
record Point(int x, int y) { }
The Java compiler will generate appropriate constructor, getters and setters for all fields, equals(), hashCode() and toString() methods for a record type. The record type Point above is equivalent to code the following class:
public class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public void setX(int x) { this.x = x; } public int getX() { return this.x; } public void setY(int y) { this.y = y; } public int getY() { return this.y; } public boolean equals(Object obj) { // implement equals based on fields x and y } public int hashCode() { // implement hashCode based on fields x and y } public String toString() { // implement toString based on fields x and y } }
So as you can see, with the new record type, you can save a lot of time when coding such POJO classes. You also avoid error-prone implementation of equals() and hashCode() if you do it by yourself.
The record type feature is under review in JDK 14 (preview) and it will be finalized in future JDK releases.
See all keywords in Java.
Other Java Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand abstraction in Java
- Understand encapsulation in Java
- Understand inheritance in Java
- Understand polymorphism in Java
Comments