Sub topic 10
What Records Cannot Do
In the last few chapters you saw how much a record gives you for free. You get a constructor, accessor methods, equals, hashCode, and toString, all from one line of code. That convenience has a price. A record follows strict rules, and the compiler enforces them.
This chapter covers those rules. For each one you will see what the rule is, why it exists, and what to do instead. Knowing the limits saves you from confusing compiler errors. It also helps you tell when a record is the wrong tool.
Why Records Have Rules at All
A record is a promise. When you write record Point(int x, int y) {}, you are telling Java and every reader: "A Point is exactly an x and a y. Nothing more, nothing hidden."
A component is one of the values listed in the record's header, like x and y here. Java builds everything from the components. Two points are equal if their components are equal. toString prints the components. If a record could hold hidden extra data, or be changed by a subclass, those generated methods could be wrong.
So every restriction below protects one idea: the components are the whole story.
Rule 1: A Record Is Final
Final means no other class can extend it. Every record is final automatically, even if you don't write the word.
Suppose you try this:
record Point(int x, int y) {}class Point3D extends Point { ... }
The compiler rejects the second line with an error like cannot inherit from final Point.
Why? Imagine Point3D added a z field. Then a Point3D(1, 2, 5) and a Point(1, 2) might count as "equal", because equals only looks at x and y. Making records final rules out that bug.
What to do instead: use composition. Composition means one object holds another as a field (or here, as a component), instead of inheriting from it.
record Point(int x, int y) {}
record Point3D(Point flat, int z) {}
public class Main {
public static void main(String[] args) {
Point3D p = new Point3D(new Point(1, 2), 5);
System.out.println(p); // Point3D[flat=Point[x=1, y=2], z=5]
System.out.println(p.flat().x()); // 1
}
}Rule 2: A Record Cannot Extend Another Class
A record also cannot extend anything itself. Every record already has a parent class: java.lang.Record. Java adds it for you. Since a Java class can only have one parent, there is no room for another.
If you write record Point(int x, int y) extends Object {}, the compiler doesn't even understand the line. You get a syntax error, because extends is simply not allowed after a record header.
What to do instead: a record can implement interfaces, as many as you like. An interface is a list of methods a type promises to have. This is how records share behavior.
Rule 3: No Extra Instance Fields
An instance field is a variable that each object has its own copy of. In a normal class you can add as many as you want. In a record, the only instance fields are the ones Java creates from the components.
If you try to add one inside the body, like private double cachedArea;, the compiler stops you. The error says roughly field declaration must be static, and it suggests turning the field into a record component.
This is the rule beginners hit most often. It usually comes up when you want to store a value you can calculate from the components, such as an area or a full name.
What to do instead: you have three options.
- Compute it in a method. This is usually the best choice. The value is always correct, because it is worked out from the components each time.
- Make it a component. Do this if it really is part of the data.
- Use a static field if the value belongs to the type as a whole, not to one object. A static field has one shared copy for the whole type. Records allow static fields.
interface HasArea {
double area();
}
record Rectangle(double width, double height) implements HasArea, Comparable<Rectangle> {
// Allowed: static fields belong to the type, not to each object.
static final Rectangle UNIT = new Rectangle(1, 1);
// Derived value: computed from the components, never stored.
public double area() {
return width * height;
}
public int compareTo(Rectangle other) {
return Double.compare(area(), other.area());
}
}
public class Main {
public static void main(String[] args) {
Rectangle r = new Rectangle(3, 4);
System.out.println(r.area()); // 12.0
System.out.println(r.compareTo(Rectangle.UNIT) > 0); // true
System.out.println(Rectangle.UNIT); // Rectangle[width=1.0, height=1.0]
}
}Rule 4: Component Fields Are Private and Final
Each component becomes a field that is private and final. Private means only code inside the record can see the field. Final means it gets a value once, in the constructor, and can never be reassigned.
So a setter like this will not compile:
void setWidth(double w) { this.width = w; }
The error is cannot assign a value to final variable width.
What to do instead: write a "with" method. It returns a new record with one component changed and leaves the original alone. Many Java developers call these "withers".
record Rectangle(double width, double height) {
Rectangle withWidth(double newWidth) {
return new Rectangle(newWidth, height);
}
Rectangle withHeight(double newHeight) {
return new Rectangle(width, newHeight);
}
}
public class Main {
public static void main(String[] args) {
Rectangle small = new Rectangle(2, 3);
Rectangle wide = small.withWidth(10);
System.out.println(small); // Rectangle[width=2.0, height=3.0]
System.out.println(wide); // Rectangle[width=10.0, height=3.0]
}
}Note that final only stops you from reassigning a field. If a component is a mutable object, such as a List, the object itself can still change. The chapter "Shallow Immutability and Defensive Copies" covers that gap.
Rule 5: Smaller Rules Worth Knowing
You will see these less often, but they still produce compiler errors.
| What you try | Allowed? | Why, or what to do instead |
|---|---|---|
| `abstract record Shape(...)` | No | A record is always a complete, final type. Use a sealed interface for a family of shapes. |
| An instance initializer block `{ ... }` in the body | No | Put the setup code in a compact constructor instead. |
| A `static { ... }` block | Yes | Static setup is fine. It runs once for the type. |
| A nested record inside a class | Yes | It is automatically `static`, so it cannot use the outer object's fields. |
| A record declared inside a method | Yes | This is called a local record. Handy for short-lived groupings of values. |
| Generic records, like `record Pair<A, B>(A first, B second)` | Yes | Works just like a generic class. |
| Writing your own accessor `x()` | Yes | It must be `public` and return the component's exact type. |
| A `native` method | No | Records are meant to be plain Java data. |
Here is the accessor rule in action. You can replace a generated accessor, for example to return a trimmed name. If you forget public, or change the return type, the compiler refuses.
record User(String name) {
// Custom accessor: must be public and must return String.
public String name() {
return name.trim();
}
}
public class Main {
public static void main(String[] args) {
User u = new User(" Ada ");
System.out.println("[" + u.name() + "]"); // [Ada]
}
}When the Rules Tell You to Use a Class
Each rule points to a situation where a regular class fits better:
- You need a parent class to inherit from, or other classes need to extend yours.
- You need hidden state: a cache, a counter, or a connection.
- The object must change over time, through setters.
- A framework requires a no-argument constructor and setters. Some older database and form-binding libraries work this way.
If none of these apply, and your type is "just these values", a record is usually the right choice.
Summary
- Records are final. Use composition instead of inheritance.
- Records cannot extend a class because they already extend
java.lang.Record. They can implement interfaces. - Records cannot add instance fields. Compute derived values in methods, or use static fields for shared values.
- Component fields are private and final. Return a new record from a "with" method instead of writing a setter.
- Custom accessors must be
publicand keep the exact return type.
Exercise
You want a record Person(String first, String last) that also stores a fullName field, so it is computed once. Why won't this compile, and how should you rewrite it?
Show answer
Records cannot declare extra instance fields, so private String fullName; triggers a "field declaration must be static" error. Remove the field and add a method instead: public String fullName() { return first + " " + last; }. The value is computed from the components each time, so it can never get out of date.
Exercise
A teammate writes record Temperature(double celsius) {} and then class PreciseTemperature extends Temperature { ... }. What error do they get, and what is a record-friendly alternative?
Show answer
They get "cannot inherit from final Temperature", because every record is implicitly final. One alternative is composition, for example record PreciseTemperature(Temperature base, int decimals) {}. Another is a shared interface that both types implement.
Exercise
Write a "with" method for record Account(String owner, long balance) that returns a copy with a new balance. Then explain why void setBalance(long b) { this.balance = b; } fails.
Show answer
Account withBalance(long newBalance) { return new Account(owner, newBalance); }. The setter fails because component fields are final. After the constructor runs they cannot be reassigned, and the compiler reports "cannot assign a value to final variable balance".