86. Iterating what we cannot have in a record
There are several artifacts that we cannot have in a Java record. The top 5 list includes:Let’s tackle them one by one.
A record cannot extend another class
Since a record already extends java.lang.Record and Java doesn’t support multiple inheritances, we cannot write a record that extends another class:
public record MelonRecord(String type, float weight)
extends Cucurbitaceae {…}
This snippet doesn’t compile.
A record cannot be extended
Java records are final classes, so they cannot be extended:
public class PumpkinClass extends MelonRecord {…}
This snippet doesn’t compile.
A record cannot be enriched with instance fields
When we declare a record, we also provide the components that become the instance fields of the records. Later, we cannot add more instance fields as we do in a typical class:
public record MelonRecord(String type, float weight) {
private String color;
private final String color;
}
This snippet doesn’t compile.
A record cannot have private constructors
Sometimes we create classes with private constructors that expose static factories for creating instances. Basically, we call the constructor indirectly via a static factory method. This practice is not available in a Java record because private canonical/compact constructors are not allowed:
public record MelonRecord(String type, float weight) {
private MelonRecord(String type, float weight) {
this.type = type;
this.weight = weight;
}
public static MelonRecord newInstance(
String type, float weight) {
return new MelonRecord(type, weight);
}
}
This snippet doesn’t compile.
A record cannot have setters
As you saw, a Java record exposes a getter (accessor method) for each of its components. These getters have the same names as components (for type we have type(), not getType()). On the other hand, we cannot have setters since the fields corresponding to the given components are final:
public record MelonRecord(String type, float weight) {
public void setType(String type) {
this.type = type;
}
public void setWeight(float weight) {
this.weight = weight;
}
}
This snippet doesn’t compile. Well, the list of artifacts that cannot be added to a Java record remains open, but these are the most common.