Java Records: Compact Constructors, Accessors and Customization (OCP 21)
Java records for the OCP 21 exam: encapsulation and why records exist, the members the compiler generates, long, compact and overloaded constructors, transforming parameters, immutability, implementing interfaces, and what records may and may not declare.
kvi5hnuCode Sprout team member7 min readOn this page
Much of the code in a Java program exists only to carry data: a booking, a coordinate, an API response. Before records, each of these classes needed private fields, a constructor, getters, equals, hashCode and toString, which was dozens of lines that all had to stay in sync. A record (standard since Java 16) gives you all of that from a single line.
Encapsulation first
Encapsulation means hiding a class's data behind its methods, so that callers can't put an object into an invalid state:
public class Sensor {
int reading; // package access: any class in the package can write -999
}
The encapsulated version makes the field private and controls access through methods:
public final class Sensor {
private final int reading;
public Sensor(int reading) {
if (reading < -50) throw new IllegalArgumentException(); // guard
this.reading = reading;
}
public int getReading() { return reading; } // accessor ("getter")
}
Encapsulation needs only private fields. Getters and setters are optional. With no setters and with final fields, the class above is also immutable (article 36). A record is the compact way to write exactly this kind of class.
Declaring a record
public record Kite(int lines, String color) { }
The parameter-like list after the name declares the record's components. From that one line the compiler generates:

- a
private finalfield for each component - the canonical constructor, with the parameters in component order
- a public accessor per component, named exactly like the component (
lines(), notgetLines()) equals(),hashCode()andtoString()that use every component
var k = new Kite(2, "red");
System.out.println(k); // Kite[lines=2, color=red]
System.out.println(k.lines()); // 2
var c = new Kite(2, "red");
System.out.println(k.equals(c)); // true: same component values
System.out.println(k == c); // false: still two objects
new Kite("red", 2); // DOES NOT COMPILE: order and types must match
new Kite("red"); // DOES NOT COMPILE: no such constructor
k.lines = 3; // DOES NOT COMPILE: the field is private (and final)
A record with no components, record Nothing() { }, is legal. Its toString() prints Nothing[].
equals compares the fields using Objects.equals for references and value equality for primitives. An array component is therefore compared by reference, so two records holding equal-content arrays aren't equal.
Constructors
The long (canonical) constructor
You can write the canonical constructor yourself. You must then assign every field, as with any final field:
public record Kite(int lines, String color) {
public Kite(int lines, String color) {
if (lines < 1) throw new IllegalArgumentException();
this.lines = lines;
this.color = color;
}
}
If you leave out an assignment, the compiler reports "variable color might not have been initialized". The canonical constructor must be at least as accessible as the record. In a public record, a package-access canonical constructor fails with "attempting to assign stronger access privileges; was public".
The compact constructor
Writing out every assignment brings back the boilerplate records were meant to remove. The compact constructor solves that. It's the canonical constructor with no parameter list at all:
public record Kite(int lines, String color) {
public Kite { // no parentheses
if (lines < 1) throw new IllegalArgumentException("lines");
color = color.strip().toLowerCase(); // transform the PARAMETER
} // fields are assigned here, automatically
}
How it works:
- The body runs first, using the constructor parameters.
- At the end, the compiler assigns each field from the (possibly reassigned) parameter. That makes the compact constructor the place for validation and normalization, such as defensive copies with
List.copyOf(article 36). - You can't assign the fields yourself:
this.color = ...fails with "cannot assign a value to final variable color". - You can't
returnearly ("compact constructor must not have return statements"). Kite() { }with empty parentheses is not a compact constructor. It's a no-argument overload, and it fails because it doesn't callthis(...).- A record can have either a compact or a long canonical constructor, not both. They're the same constructor.
Overloaded constructors
Any constructor with a different parameter list is an overload, and it must begin with this(...), eventually reaching the canonical constructor. Without it, javac reports "constructor is not canonical, so it must invoke another constructor".
public record Kite(int lines, String color) {
public Kite(String color) { this(1, color); } // OK
public Kite() { this("blue"); } // OK: chains to Kite(String)
public Kite(int lines, String a, String b) {
this(lines + 1, a + b);
lines = 10; // compiles, but only changes the parameter
this.lines = 20; // DOES NOT COMPILE: already assigned by this(...)
}
}
Transformations in an overloaded constructor can only happen inside the arguments to this(...), because once that call returns, every field is set. Cycles such as Kite(String) calling Kite(int) calling Kite(String) fail with "recursive constructor invocation", just as in classes.
In Java 21 nothing may come before this(...). Java 25's flexible constructor bodies (article 32) allow validation statements before it, as long as they don't use this.
Immutability and inheritance
- Records are implicitly
final. Writingfinal recordis allowed but redundant, and no class can extend a record. - Records can't extend anything, because they implicitly extend
java.lang.Record.record B() extends A { }doesn't compile. - Records can implement interfaces, including sealed ones (article 40), as long as they implement every abstract method.
- All instance fields are
final, and there are no setters. To "change" a record, create a new one, typically with awithXmethod. staticfields are allowed and don't have to befinal:
public record Ticket(String name, int number) {
private static int issued = 0;
public Ticket(String name) { this(name, ++issued); }
}
Records are shallowly immutable. A List component can still be modified unless the compact constructor copies it.
Customizing a record
A record body may contain:
- constructors (compact, long or overloaded)
- instance methods, including overrides of the generated accessors,
equals,hashCodeandtoString - static fields, static methods and static initializers
- nested types: classes, interfaces, enums, records and annotations
public record Kite(int lines, String color) {
static { System.out.print("loading "); } // static initializer: OK
@Override public String toString() { return color + " kite"; }
public int lines() { return Math.max(lines, 1); } // accessor override
boolean isStunt() { return lines >= 2; }
static Kite of(String c) { return new Kite(1, c); }
}
A record body may not contain:
| Not allowed | javac message |
|---|---|
instance fields (even private final) | "field declaration must be static (consider replacing field with record component)" |
| instance initializer blocks | "instance initializers not allowed in records" |
abstract methods | the record isn't abstract and can't be |
| setters that assign fields | "cannot assign a value to final variable" |
Accessor overrides have extra rules. They must be public and return exactly the component type. int lines() with package access fails, and so does public Integer lines(). Component declarations can't have modifiers (record Kite(final int lines) fails), and a few names are reserved, such as hashCode, toString, getClass and clone ("illegal record component name").
Records can be generic (record Pair<A, B>(A first, B second)), can have varargs components (String... members), and can be declared locally inside a method. Local records are implicitly static, so they can't use the method's local variables.
What's current
- Records have been final since Java 16 and are unchanged through Java 25.
- Java 25's flexible constructor bodies also allow validation code before
this(...)in a non-canonical record constructor.
Exam traps from this article
A complete example
A hotel Booking record validates and normalizes its data in a compact constructor, offers an overloaded constructor and helper methods, implements Comparable, and shows generated equals and hashCode deduplicating bookings in a HashSet.
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Solution {
record Booking(String guest, LocalDate checkIn, int nights, List<String> extras)
implements Comparable<Booking> {
private static int created; // static fields are allowed
// Compact constructor: no parameter list; validates and normalizes the parameters
Booking {
if (nights < 1) throw new IllegalArgumentException("nights must be >= 1");
guest = guest.strip(); // reassigns the parameter
extras = List.copyOf(extras); // defensive, unmodifiable copy
created++;
} // fields assigned here, implicitly
// Overloaded constructor: must start with this(...)
Booking(String guest, LocalDate checkIn) {
this(guest, checkIn, 1, List.of());
}
// Extra instance methods
LocalDate checkOut() { return checkIn.plusDays(nights); }
Booking withNights(int n) { // "modify" by copying
return new Booking(guest, checkIn, n, extras);
}
@Override public int compareTo(Booking other) {
return checkIn.compareTo(other.checkIn);
}
static int created() { return created; }
}
public static void main(String[] args) {
List<String> wanted = new ArrayList<>(List.of("breakfast"));
Booking a = new Booking(" Ana Ruiz ", LocalDate.of(2026, 7, 10), 3, wanted);
wanted.add("minibar"); // no effect on a
System.out.println(a);
System.out.println("guest='" + a.guest() + "', check-out " + a.checkOut());
Booking b = new Booking("Ana Ruiz", LocalDate.of(2026, 7, 10), 3, List.of("breakfast"));
System.out.println("a.equals(b): " + a.equals(b) + ", same hash: " + (a.hashCode() == b.hashCode())
+ ", a == b: " + (a == b));
Set<Booking> unique = new HashSet<>(List.of(a, b, a.withNights(5)));
System.out.println("unique bookings: " + unique.size());
Booking walkIn = new Booking("Li Wei", LocalDate.of(2026, 7, 2));
System.out.println(walkIn + " sorts before a: " + (walkIn.compareTo(a) < 0));
try {
a.extras().add("spa");
} catch (UnsupportedOperationException e) {
System.out.println("extras are unmodifiable");
}
try {
new Booking("Bo", LocalDate.of(2026, 8, 1), 0, List.of());
} catch (IllegalArgumentException e) {
System.out.println("rejected: " + e.getMessage());
}
System.out.println("records created: " + Booking.created());
}
}
Output:
Booking[guest=Ana Ruiz, checkIn=2026-07-10, nights=3, extras=[breakfast]]
guest='Ana Ruiz', check-out 2026-07-13
a.equals(b): true, same hash: true, a == b: false
unique bookings: 2
Booking[guest=Li Wei, checkIn=2026-07-02, nights=1, extras=[]] sorts before a: true
extras are unmodifiable
rejected: nights must be >= 1
records created: 4
Points to notice:
- The compact constructor trims
guestand copiesextras. The caller's laterwanted.add("minibar")has no effect. aandbwere built separately but hold equal components, soequalsistrueand the hash codes match. TheHashSetkeeps one of them, plus the 5-night copy.withNightsreturns a new record instead of changinga.- The rejected booking throws before
created++, so only four records count as created.
Common questions
Are records just "data classes" with no behavior? No. They can have any number of methods. They just can't hold extra instance state beyond their components.
Can I use records as JPA entities or JavaBeans? Not usually. Those frameworks expect no-argument constructors and setters. Records fit DTOs, value objects, map keys and the results of methods that return several values.
Do records replace Lombok-style generated classes? For immutable data carriers, yes. That's one of the main reasons the feature was added.
Summary
- A record declares its components once and gets private final fields, a canonical constructor, accessors,
equals,hashCodeandtoString. - Write the canonical constructor in long form (assign every field) or compact form (no parentheses, transform the parameters, automatic assignment).
- Overloaded constructors must call
this(...)first. Fields can't be reassigned after that. - Records are final, can't extend classes, can implement interfaces, and allow static members but no instance fields or instance initializers.
- Accessor overrides must be public with the exact type. Generated
equalscompares fields.
Practice quiz
Test yourself with the records quiz: 10 exam-style questions with explanations.
Previous: Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
Next: Java Record Patterns: Deconstruction, Nesting and switch (OCP 21)
Related reading
- Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
- Java Enums: Values, Constructors, Fields, Methods and switch (OCP 21)
- Java Interface default, static and private Methods (OCP 21)
- Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
- Java Immutable Objects and Defensive Copies (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.