Sub topic 3
What Records Cannot Do
A record is a short class made to hold data. That short form comes with some rules. This chapter explains those rules, then shows when a record, an enum, or a plain class fits best.
The Rules for Records
- Records are final. No other class can extend a record.
- Records cannot extend a class. A record already extends
java.lang.Record. It can still implement interfaces. - Records have no extra instance fields. The only data a record holds is its components. You can still add static fields.
- Record fields are final. After you create a record, you cannot change its fields.
Shallow Immutability and Defensive Copies
An immutable object is an object whose data cannot change after it is created. Records are only shallowly immutable. A field cannot point to a new object, but the object it points to can still change. Suppose a component is a List. If a caller keeps a reference to that list, the caller can change it later and the record's data changes too.
The fix is a defensive copy, which means the record stores its own copy of the data:
import java.util.ArrayList;
import java.util.List;
record Team(String name, List<String> members) {
Team {
members = List.copyOf(members);
}
}
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ana"));
Team team = new Team("Blue", names);
names.add("Ben");
System.out.println(team.members()); // [Ana]
}
}Record, Enum, or Class?
| Use | When |
|---|---|
| Enum | You have a fixed list of named values, such as days or coins |
| Record | You need to carry data that does not change, such as a point |
| Class | You need fields that change, inheritance, or hidden state |
Sealed Interfaces and Pattern Matching
A sealed interface is an interface that only the types you name can implement. Pattern matching is a way to check an object's type and pull out its data in one step. In Java 21, you can combine the two in a switch. The compiler knows every possible type, so you don't need a default branch.
sealed interface Shape permits Circle, Square {}
record Circle(double radius) implements Shape {}
record Square(double side) implements Shape {}
public class Shapes {
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Square(double side) -> side * side;
};
}
public static void main(String[] args) {
System.out.println(area(new Square(3))); // 9.0
}
}The line case Square(double side) is a record pattern. It unpacks the record's component straight into a variable named side.
Exercise
A record has a List component. Why should its compact constructor call List.copyOf?
Show answer
Records are only shallowly immutable. Without a copy, the caller could change the original list, and that would change the record's data. List.copyOf stores a separate copy that cannot be changed.