Advanced level · Module 2: Modern Java Language and Design · Lesson 1 of 4
Records, Enums and Sealed Types
Model data concisely with records, fixed sets of values with enums, and closed hierarchies with sealed interfaces.
In this lesson you will
- Create records with validation in compact constructors
- Use enums with fields and sealed interfaces with switch pattern matching
Key concepts
recordcompact constructorenum with fieldssealed interfacepattern matching for switch
The lesson
A record is a concise, immutable data class: record Money(long amount, String currency) {}. Java generates the constructor, accessors, equals, hashCode and toString. A compact constructor validates values: record Money(long amount, String currency) { Money { if (amount < 0) throw new IllegalArgumentException("negative"); } }.
An enum lists a fixed set of values and can carry data and behaviour: enum Region { JUBA(1.0), WAU(1.15); final double transportFactor; … }. Use enums instead of String constants so typos become compile errors.
A sealed interface lists exactly which classes may implement it: sealed interface Shape permits Circle, Square {}. A switch over a sealed type can then be exhaustive without a default branch, and the compiler warns you if a new subtype is not handled.
Step by step
- Convert a Product class into a record and remove the generated boilerplate.
- Add validation in a compact constructor.
- Replace String region codes with an enum that has a field.
- Model payment results as a sealed interface and handle them with a switch.
Practice activity
Model an order system with records for OrderLine and Money, an enum for OrderStatus with allowed transitions, and a sealed result type for payment outcomes.
Expected result: Invalid values are rejected on construction and every payment outcome is handled in an exhaustive switch.
Check your understanding
-
Which methods does a record generate automatically?
Show answer
The canonical constructor, accessors, equals, hashCode and toString.
-
What is the benefit of a sealed interface in a switch?
Show answer
The compiler knows every subtype, so it can check the switch is exhaustive.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.