Object-Oriented Java · 9 min read · Beginner
Classes, Encapsulation & Records
Build encapsulated Java classes with private fields, and eliminate boilerplate for immutable data using Java records.
What you'll learn
- Encapsulate mutable state with private fields and public methods
- Model immutable data transfer objects cleanly with Java record
- Validate inputs inside a compact record constructor
Traditional Java classes required dozens of lines for constructors, getters, equals(), hashCode(), and toString(). Modern Java solves this with record: a single line declares an immutable data carrier with all of those generated automatically.
Class vs. Record
- Use
recordfor immutable data (API DTOs, coordinates, configuration, events). - Use
classwhen an entity owns mutable state or complex lifecycle behavior.
Fill-in-the-Blank Exercise
Declare an Immutable Java Record
Define a Course record with a String title and int lessons.
public Course(String title, int lessons) {
public Course {
if (lessons <= 0) throw new IllegalArgumentException("Lessons must be positive");
}
}
var c = Course("Java 21", 6);Interactive Code Lab
JavaRecordsDemo.java
Expected OutputClick “Run Live” to compile with OpenJDK 21
Course[title=Java 21 Essentials, lessons=6] Title: Java 21 Essentials
Check Your Understanding
Score: 0 / 1
1. What does a Java record automatically generate for you?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.