ReviseAlgo Logo

Modern Java Features

Record Classes

Create immutable data carrier classes using Records introduced in Java 16.

Interview: Commonly tested on Record structure: immutability rules, custom constructor declarations, and inheritance restrictions.

Last Updated: June 13, 2026 10 min read

Introduced in Java 16, Record Classes are special immutable classes designed to act as transparent data carriers, eliminating boilerplate getter, hashCode, equals, and toString definitions.

Core Idea

Records are immutable: fields are implicitly private final, and standard constructor accessors are auto-generated.

Why It Matters

Replaces boilerplate Lombok dependencies and verbose POJO declarations with single-line code declarations.

Interview Lens

Tests compact constructor validation rules and inheritance constraints (records cannot extend other classes).

Record Architecture and Rules

  • Immutability: All header fields compile into private final instance fields. Accessor methods match field names (e.g. user.email(), not getUserEmail()).
  • Inheritance Restriction: Records are implicitly final. They cannot extend another class, and no other class can extend them. They can, however, implement interfaces.
  • Compact Constructors: Allows writing validation logic without redeclaring parameters and assignments (fields are assigned automatically at the end of the block).

Code Walkthrough

This program demonstrates a Record declaration with a compact constructor validation check.

public class RecordDemo {
    public record User(String email, int age) {
        // Compact Constructor: parameters are implicit
        public User {
            if (email == null || email.isBlank()) {
                throw new IllegalArgumentException("Email required");
            }
        }
    }

public static void main(String[] args) { User user = new User("alice@example.com", 28); System.out.println(user); // Auto-generated toString() System.out.println("Email: " + user.email()); // Accessor method } }

Interview-Relevant Information

Q: Can you define instance fields inside a record's body?
Answer: No. You cannot declare additional instance fields inside a record's body (e.g. private int value;). All instance state variables must be declared in the record header. You are only allowed to define static fields, static methods, or instance methods in the body.

Quick Checklist

How do record getter signatures differ from POJOs? Can a record extend another class? If yes, you understand Record classes.

Use Cases

Defining DTOs (Data Transfer Objects) for REST controllers.

Modeling immutable keys inside HashMap structures.

Common Mistakes

Attempting to inherit from a base class using a record (records already inherit from java.lang.Record).

Calling getters using 'get' prefix (records use direct field name methods).