IntermediateLesson 9 of 16
Records & Enums – Java
Immutable data classes without boilerplate and fixed sets of values.
A record (Java 16+) is an immutable data class. Java automatically generates the constructor, accessor methods (x(), not getX()), equals, hashCode and toString.
record Punkt(int x, int y) {}
var p = new Punkt(1, 2);
System.out.println(p); // Punkt[x=1, y=2]
System.out.println(p.x() + " " + p.y()); // 1 2
System.out.println(p.equals(new Punkt(1, 2))); // trueIn the compact constructor you validate values. You may also add methods and static factories. Records are shallowly immutable: fields are final, but a contained List object can change.
record Konto(String inhaber, double saldo) {
Konto { // compact constructor
if (saldo < 0) throw new IllegalArgumentException("Balance negative");
}
Konto einzahlen(double betrag) { // "wither": returns a new object
return new Konto(inhaber, saldo + betrag);
}
static Konto leer(String inhaber) { return new Konto(inhaber, 0); }
}
var k = Konto.leer("Ada").einzahlen(25);
System.out.println(k); // Konto[inhaber=Ada, saldo=25.0]An enum defines a fixed set of constants and can have fields, constructors and methods:
enum Wochentag {
MONTAG(true), SAMSTAG(false), SONNTAG(false);
private final boolean arbeitstag;
Wochentag(boolean arbeitstag) { this.arbeitstag = arbeitstag; }
boolean istArbeitstag() { return arbeitstag; }
}
for (Wochentag t : Wochentag.values()) {
System.out.println(t + " " + t.istArbeitstag() + " " + t.ordinal());
}
Wochentag w = Wochentag.valueOf("MONTAG");
String text = switch (w) {
case MONTAG -> "Start of the week";
case SAMSTAG, SONNTAG -> "Weekend"; // no default needed: all cases covered
};TipUse records for all "data carrier" classes (DTOs, return values with several fields, map keys). Use enums instead of strings or magic numbers for fixed sets of choices.