Core Java

15 โ€” Records & Sealed Classes

Previous: 14 Static & Enums ยท Next: 16 Exceptions

โ–ถ๏ธ java pkg1core/core16RecordsDemo.java ยท java pkg1core/core17SealedClassesDemo.java


Records (Java 16+) โ€” data carriers

java
1record Point(int x, int y) {}

Compiler auto-generates:

  • Constructor
  • x() and y() accessors (not getX())
  • equals, hashCode, toString
java
1Point p = new Point(3, 4);2System.out.println(p.x());    // 3

Compact constructor โ€” validation

java
1record User(String email) {2    User {3        if (!email.contains("@")) throw new IllegalArgumentException();4    }5}

๐Ÿ’ก Use records for DTOs, value objects, pattern matching โ€” not JPA entities without care.


Sealed classes (Java 17+) โ€” controlled hierarchy

java
1sealed interface Expr permits Constant, Add {2    double eval();3}4record Constant(double value) implements Expr {5    public double eval() { return value; }6}7record Add(Expr left, Expr right) implements Expr {8    public double eval() { return left.eval() + right.eval(); }9}

Only listed classes can extend/implement. Enables exhaustive switch:

java
1double result = switch (expr) {2    case Constant c -> c.value();3    case Add a      -> a.left().eval() + a.right().eval();4};

Why sealed + records together?

Modern Java algebraic data types โ€” model closed sets of variants (expressions, AST nodes, payment types) with compile-time safety.

Milestone: You completed OOP (chapters 10โ€“15). ๐ŸŽ‰

Next โ†’ 16 Exceptions Related โ†’ 01 Core Java