Records, enums and sealed types
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
Modern ways to model data
Many Java classes exist only to carry data. You write fields, a constructor, getters, equals, hashCode and toString, and the real idea is buried in boilerplate. Java 16 added records to fix this. Java 17 finalised sealed types, and Java 21 finalised pattern matching for switch and record patterns. Together they make a style of programming that I find compact and very safe. This lesson is the one to study if you learned Java years ago.
Records
A record is a class for immutable data. You list its components, and the compiler generates the fields, the constructor, accessor methods, equals, hashCode and toString.
Enums
An enum is a type with a fixed set of constants. Use enums instead of strings or magic numbers for things like order status or days of the week. An enum can have fields, a constructor and methods.
Sealed types
A sealed interface or class names exactly which types may implement or extend it, using permits. The compiler then knows the complete list. A switch over such a type does not need a default branch, and adding a new subtype makes every incomplete switch fail to compile. That moves a whole class of bugs from runtime to compile time.
import java.util.List;
public class Main {
public static void main(String[] args) {
// Records
Point p = new Point(3, 4);
System.out.println(p); // Point[x=3, y=4]
System.out.println(p.equals(new Point(3, 4))); // true
System.out.println(p.distanceFromOrigin());
try {
new Email("not-an-email");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
// Enums
Status status = Status.SHIPPED;
System.out.println(status + " " + status.label() + " " + status.isFinal());
for (Status s : Status.values()) {
System.out.print(s.name() + " ");
}
System.out.println();
System.out.println(Status.valueOf("PAID").label());
// Sealed hierarchy and pattern matching
List<Shape> shapes = List.of(
new Circle(1.5),
new Rectangle(3, 4),
new Triangle(3, 4, 5));
for (Shape shape : shapes) {
System.out.printf("%s -> area %.2f%n", describe(shape), area(shape));
}
// Record patterns can pull the parts out directly
Object thing = new Point(10, 20);
if (thing instanceof Point(int x, int y)) {
System.out.println("x + y = " + (x + y));
}
}
record Point(int x, int y) {
double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
}
// A compact constructor validates the components
record Email(String value) {
Email {
if (value == null || !value.contains("@")) {
throw new IllegalArgumentException("Invalid email: " + value);
}
value = value.toLowerCase();
}
}
enum Status {
NEW("New order", false),
PAID("Payment received", false),
SHIPPED("On its way", false),
DELIVERED("Delivered", true);
private final String label;
private final boolean isFinal;
Status(String label, boolean isFinal) {
this.label = label;
this.isFinal = isFinal;
}
String label() { return label; }
boolean isFinal() { return isFinal; }
}
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Triangle(double a, double b, double c) implements Shape {}
// No default branch: the compiler checks that every case is covered
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle(double w, double h) -> w * h;
case Triangle t -> {
double s = (t.a() + t.b() + t.c()) / 2;
yield Math.sqrt(s * (s - t.a()) * (s - t.b()) * (s - t.c()));
}
};
}
static String describe(Shape shape) {
return switch (shape) {
case Circle c when c.radius() > 1 -> "big circle";
case Circle c -> "small circle";
case Rectangle r when r.width() == r.height() -> "square";
case Rectangle r -> "rectangle";
case Triangle t -> "triangle";
};
}
}
Walking through it
record Point(int x, int y) is the whole declaration. The printed form shows the component names, and equals compares values, so two points with the same coordinates are equal. The accessors are named like the components: p.x(), not getX(). Records are shallowly immutable. Their fields are final, but if a component is a mutable list, the list can still change.
A record can have its own methods, such as distanceFromOrigin. It can also have a compact constructor, as in Email. The compact constructor has no parameter list. It runs before the fields are assigned, so you can validate and normalise the components. Here I reject text without an @ and convert the address to lowercase. This gives you a small type that can never hold invalid data, which is far better than passing raw strings around.
The Status enum has a constructor and two fields. values() returns all constants in order, and valueOf finds one by name, throwing IllegalArgumentException if the name is wrong. Enums work well in switch expressions, and they are safe to compare with ==.
The Shape hierarchy is sealed, and all permitted types are records in the same file. In area, the switch covers all three and has no default. Try deleting the Triangle case, and the compiler will refuse to compile. Now imagine adding a fourth shape in six months. Every switch like this one will show an error until it handles the new shape. That is the safety net.
The switch uses three pattern forms. case Circle c is a type pattern that binds the variable c. case Rectangle(double w, double h) is a record pattern that takes the object apart. case Circle c when c.radius() > 1 adds a guard condition. Order matters: the guarded circle must come before the general circle.
Common mistakes
- Adding
defaultto a switch over a sealed type. It silences the compiler warning when you add a new subtype, which defeats the purpose. - Putting a mutable list in a record and assuming it is immutable. Copy it with
List.copyOfin the compact constructor. - Dominated patterns. A broad pattern before a narrow one makes the narrow one unreachable, which is a compile error.
Try it yourself
- Create a record
Money(BigDecimal amount, String currency)that rejects negative amounts. - Write an enum
Levelwith LOW, MEDIUM, HIGH and a numeric weight, and a method that returns the next level. - Make a sealed interface
PaymentMethodwith recordsCard,BankTransferandCash, and write a switch that returns the fee for each.
import java.util.List;
public class Main {
public static void main(String[] args) {
// Records
Point p = new Point(3, 4);
System.out.println(p); // Point[x=3, y=4]
System.out.println(p.equals(new Point(3, 4))); // true
System.out.println(p.distanceFromOrigin());
try {
new Email("not-an-email");
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
// Enums
Status status = Status.SHIPPED;
System.out.println(status + " " + status.label() + " " + status.isFinal());
for (Status s : Status.values()) {
System.out.print(s.name() + " ");
}
System.out.println();
System.out.println(Status.valueOf("PAID").label());
// Sealed hierarchy and pattern matching
List<Shape> shapes = List.of(
new Circle(1.5),
new Rectangle(3, 4),
new Triangle(3, 4, 5));
for (Shape shape : shapes) {
System.out.printf("%s -> area %.2f%n", describe(shape), area(shape));
}
// Record patterns can pull the parts out directly
Object thing = new Point(10, 20);
if (thing instanceof Point(int x, int y)) {
System.out.println("x + y = " + (x + y));
}
}
record Point(int x, int y) {
double distanceFromOrigin() {
return Math.sqrt(x * x + y * y);
}
}
// A compact constructor validates the components
record Email(String value) {
Email {
if (value == null || !value.contains("@")) {
throw new IllegalArgumentException("Invalid email: " + value);
}
value = value.toLowerCase();
}
}
enum Status {
NEW("New order", false),
PAID("Payment received", false),
SHIPPED("On its way", false),
DELIVERED("Delivered", true);
private final String label;
private final boolean isFinal;
Status(String label, boolean isFinal) {
this.label = label;
this.isFinal = isFinal;
}
String label() { return label; }
boolean isFinal() { return isFinal; }
}
sealed interface Shape permits Circle, Rectangle, Triangle {}
record Circle(double radius) implements Shape {}
record Rectangle(double width, double height) implements Shape {}
record Triangle(double a, double b, double c) implements Shape {}
// No default branch: the compiler checks that every case is covered
static double area(Shape shape) {
return switch (shape) {
case Circle c -> Math.PI * c.radius() * c.radius();
case Rectangle(double w, double h) -> w * h;
case Triangle t -> {
double s = (t.a() + t.b() + t.c()) / 2;
yield Math.sqrt(s * (s - t.a()) * (s - t.b()) * (s - t.c()));
}
};
}
static String describe(Shape shape) {
return switch (shape) {
case Circle c when c.radius() > 1 -> "big circle";
case Circle c -> "small circle";
case Rectangle r when r.width() == r.height() -> "square";
case Rectangle r -> "rectangle";
case Triangle t -> "triangle";
};
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account