Skills101

AdvancedJava Programming · Lesson 20 of 29 · Updated ·

Records and Sealed Classes in Java — Data Classes in One Line and Closed Hierarchies

Much of the code in a real Java project is data carriers: classes that only hold a few values — a student's name and marks, an order's id and amount. Writing them by hand means a constructor, getters, equals, hashCode and toString, and it is easy to get one wrong. Records (Java 16) write all of that for you. Sealed classes (Java 17) solve a different problem: they let you say exactly which classes may extend a type. Together they are a big part of "modern Java", and interviewers increasingly ask about them.

1. A record in one line

record Student(String name, int marks) { }

public class Main {
    public static void main(String[] args) {
        Student a = new Student("Asha", 92);
        Student b = new Student("Asha", 92);
        System.out.println(a);                        // toString is generated
        System.out.println(a.name() + " " + a.marks()); // accessors: name(), not getName()
        System.out.println(a.equals(b) + " " + (a == b));
        System.out.println(a.hashCode() == b.hashCode());
    }
}
Student[name=Asha, marks=92]
Asha 92
true false
true

From the header record Student(String name, int marks) the compiler generates:

What the compiler writes for record Student(String name, int marks): private final fields name and marks, a constructor taking both, accessor methods name() and marks(), and equals, hashCode and toString based on both fields

GeneratedDetail
fieldsprivate final String name; private final int marks;
constructorStudent(String name, int marks) — the canonical constructor
accessorsname() and marks() — no get prefix
equals / hashCodecompare all fields, so two records with the same data are equal
toStringStudent[name=Asha, marks=92]

A record class is also automatically final (no subclass can extend it), and its fields are final, so a record object cannot change after it is created.

2. Validation with a compact constructor

You can still add checks. A compact constructor has no parameter list; the fields are assigned automatically after your code runs.

record Product(String name, double price) {
    Product {                                    // compact constructor
        if (price < 0) throw new IllegalArgumentException("price cannot be negative");
        name = name.trim();                      // you may adjust the parameters
    }

    double priceWithGst() { return price * 118 / 100; }       // normal methods are fine

    static Product free(String name) { return new Product(name, 0); }   // so are static ones
}

public class Main {
    public static void main(String[] args) {
        Product pen = new Product("  Pen ", 10);
        System.out.println(pen + " " + pen.priceWithGst());
        System.out.println(Product.free("Sticker"));
        try {
            new Product("Bag", -5);
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
Product[name=Pen, price=10.0] 11.8
Product[name=Sticker, price=0.0]
Rejected: price cannot be negative

Rules and limits

  • A record cannot extend another class (it already extends java.lang.Record), but it can implement interfaces.
  • You cannot add instance fields beyond those in the header. Static fields are allowed.
  • Records are shallowly immutable. If a component is a List, the list itself can still change. Copy it in the compact constructor with List.copyOf(list) to be safe.
import java.util.*;

record Team(String name, List<String> members) {
    Team {
        members = List.copyOf(members);   // our own unchangeable copy
    }
}

public class Main {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("Asha", "Ravi"));
        Team t = new Team("Coders", names);
        names.add("Neha");                    // changes the caller's list only
        System.out.println(t.members());
        try {
            t.members().add("Om");
        } catch (UnsupportedOperationException e) {
            System.out.println("Team members cannot be changed");
        }
    }
}
[Asha, Ravi]
Team members cannot be changed

When to use a record

  • To return two or more values from a method.
  • For data transfer objects (the body of an API request or response).
  • As keys in a HashMap or items in a HashSet — equals and hashCode are already correct.

Use a normal class when the object needs to change over time (a bank account whose balance moves) or needs to extend another class.

3. Sealed classes: a closed list of subclasses

Normally anyone can extend a non-final class or implement an interface. Sometimes you want to say: "a payment is only UPI, card or cash — nothing else". A sealed type lists its allowed subtypes with permits.

Sealed hierarchy: sealed interface Payment permits exactly three types — record Upi, record Card and final class Cash. A fourth class trying to implement Payment is a compile error

sealed interface Payment permits Upi, Card, Cash { }

record Upi(String upiId, double amount) implements Payment { }
record Card(String last4, double amount) implements Payment { }
final class Cash implements Payment {
    final double amount;
    Cash(double amount) { this.amount = amount; }
}

public class Main {
    static String describe(Payment p) {
        if (p instanceof Upi u) return "UPI from " + u.upiId() + ": " + u.amount();
        if (p instanceof Card c) return "Card ending " + c.last4() + ": " + c.amount();
        if (p instanceof Cash c) return "Cash: " + c.amount;
        throw new IllegalStateException();       // cannot happen: the list is closed
    }

    public static void main(String[] args) {
        Payment[] payments = { new Upi("asha@upi", 499), new Card("4242", 1299), new Cash(50) };
        for (Payment p : payments) System.out.println(describe(p));
    }
}
UPI from asha@upi: 499.0
Card ending 4242: 1299.0
Cash: 50.0

Each permitted subclass must say how the hierarchy continues:

Modifier on the subclassMeaning
finalnobody may extend it further (records are final automatically)
sealed … permits …it is closed too, with its own list
non-sealedopen again: anyone may extend it

The permitted classes must be in the same file, package or module as the sealed type. Here all of them are in one file, which is the simplest setup.

Why sealed classes matter

  • The compiler knows every case. From Java 21, a switch over a sealed type can check that every subtype is handled, with no default needed. If someone later adds NetBanking to the permits list, every switch that forgot it stops compiling — the bug is found at once.
  • Clear design. The code itself documents that there are exactly three kinds of payment.

This is the Java 21 form of describe (pattern matching for switch; it needs JDK 21 or later):

static String describe(Payment p) {
    return switch (p) {
        case Upi u  -> "UPI from " + u.upiId() + ": " + u.amount();
        case Card c -> "Card ending " + c.last4() + ": " + c.amount();
        case Cash c -> "Cash: " + c.amount;
    };   // no default: the compiler checks that all three are covered
}

Records + sealed interfaces + pattern matching are often called data-oriented programming: model the data as a closed set of simple records, then handle each case.

Common mistakes

  • Calling getName() on a record — the accessor is name().
  • Trying to extends a class from a record, or to add a new instance field inside the body.
  • Assuming a record holding a List is fully immutable; copy the list with List.copyOf.
  • Forgetting to mark a permitted subclass final, sealed or non-sealed (compile error).
  • Using records for objects whose state must change; use a normal class.

Quick recap

  • record Point(int x, int y) {} gives final fields, a constructor, accessors x(), y(), and equals, hashCode, toString.
  • Validate in a compact constructor; records are final and shallowly immutable.
  • Records can implement interfaces but cannot extend classes.
  • sealed … permits A, B closes a hierarchy; subclasses are final, sealed or non-sealed.
  • With Java 21 pattern-matching switch, the compiler checks that every permitted case is handled.

Practice what you learned

📝 Quiz: Records and Sealed Classes5 questions · instant answers & explanations · +10 XP · counts towards your free certificateTake the quiz →