Record classes got introduced in Java 14 as a preview feature. Record classes or just Records give us a much easier and quicker way to write Java POJO classes.
In Java, if we want to declare a POJO class, we need to write some boilerplate code such as private fields, getter and setter methods, constructors, and methods like hashCode(), equals(), and toString(). With Records, we don’t have to do all of that.
Record in Java has to be declared with a keyword record.
Examples of Record Class in Java
POJO class before Java 14:
class User { private String name; private String username; private String membershipType; private String address; public User(String name, String username, String membershipType, String address) { this.name = name; this.username = username; this.membershipType = membershipType; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMembershipType() { return membershipType; } public void setMembershipType(String membershipType) { this.membershipType = membershipType; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof User)) return false; User user = (User) o; return Objects.equals(getName(), user.getName()) && Objects.equals(getUsername(), user.getUsername()) && Objects.equals(getMembershipType(), user.getMembershipType()) && Objects.equals(getAddress(), user.getAddress()); } @Override public int hashCode() { return Objects.hash(getName(), getUsername(), getMembershipType(), getAddress()); } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", username='" + username + '\'' + ", membershipType='" + membershipType + '\'' + ", address='" + address + '\'' + '}'; } }
It’s a huge class with plenty of repetitive boilerplate code.
Same POJO using Java 14:
public record User(int name, String username, String membershipType, String address) { };
As you can see, we can create a POJO class as a one-liner Record. And we don’t have to waste time writing standard methods. Between the parentheses, we specify what fields the class should contain.
With Records, getter and setter methods, constructors, and methods like hashCode(), equals(), and toString() are being generated under the hood for us.
We can define methods within a Record, just like with classes.
public record Record1(int field1, String field2, boolean field3) { public void method() { // ... } public static void staticMethod() { // ... } }
That was all about Java Records. Proceed to the next lesson to learn more about Pattern Matching for instanceof.
Happy coding!