Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this tutorial, we’ll learn the differences between a record class and a final class in Java.

2. What Is a Record?

Record classes are special classes that act as transparent carriers for immutable data. They are immutable classes (all fields are final) and are implicitly final classes, which means they can’t be extended.

There are some restrictions that we need to keep in mind when writing a record class:

  • We cannot add the extends clause to the declaration since every record class implicitly extends the abstract class Record, and Java doesn’t allow multiple inheritance
  • We cannot declare instance variables or instance initializers in a record class
  • We cannot declare native methods in a record class

A record class declaration includes a name, type parameters (if the record is generic), a header containing the record’s components, and a body:

public record Citizen (String name, String address) {}

The Java compiler then automatically generates the private, final fields, getters, a public constructor, and the equals, hashCode, and toString methods.

Moreover, we can add instance methods as well as static fields and methods to the record body:

public record USCitizen(String firstName, String lastName, String address) {
    static int countryCode;

    // static initializer
    static {
        countryCode = 1;
    }

    public static int getCountryCode() {
        return countryCode;
    }

    public String getFullName() {
        return firstName + " " + lastName;
    }
}

The above record contains a static field, a static method, and an instance method.

3. What Is a Final Class?

Final classes cannot be extended. They are declared with the final keyword:

final class Rectangle {
    private double length;
    private double width;

    // Rest of the body
}

Here, we cannot create another class that extends the Rectangle class since it’s a final class.

4. What Are the Differences?

Records are final classes themselves. However, record classes have more constraints compared to regular final classes. On the other hand, records are more convenient to use in certain situations since they can be declared in a single line, and the compiler automatically generates everything else. We can use records if we need a simple data carrier that is immutable and won’t inherit from other classes.

5. Summary

In this short article, we learned the differences between records and final classes in Java.

As always, the code snippets used in this article are available over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.