Enums, Records, and Special Java Types

Java isn't just about classes and objects — it also gives us specialized types to make our code clearer, safer, and more expressive. In this chapter, we’ll cover three of them: Enums, Records, and Sealed Classes. These types are part of modern Java’s toolbox for writing code that communicates better with both the compiler and future developers (including you).

Enums: Defining Fixed Sets of Values

Let’s say you're writing a program that handles user roles: ADMIN, MODERATOR, USER. You could use String, but then someone might write "admn" and everything breaks. That’s where enum comes in

Enum

Why use enums?

Enum with Methods

This helps enforce logic like:

Enum Logic

Records: Fast, Immutable Data Holders

Let’s say you're modeling a Book object — just data, no behavior. Before:

Book Class

That's a lot of code. With records:

Book Record

That’s it. Java auto-generates:

When to use record:

When not to use it:

Sealed Classes: Controlling Inheritance

ava 17 introduced sealed classes. Imagine you have a class Shape, and you want to limit its subclasses to only Circle, Square, and Triangle.

Sealed Class

Why use them?

Sealed types are great for modeling finite possibilities, like API responses or commands in a system.

Quick Practice

Enum Use Case: Create an enum called DayOfWeek with days from MONDAY to SUNDAY. Add a method isWeekend().
Record Refactor: Turn your old Person class into a record. See how much cleaner it gets.
Sealed Design: Design a sealed class Notification with types like Email, SMS, and Push.

Conclusion: Cleaner Code Through Stronger Types

Java's special types let you write less code — and safer code — by being more specific about what your data is and what it can do.

You’ll see these everywhere in production code and APIs. Mastering them helps you read and write more elegant, modern Java.

What’s Next

We’ve handled elegant data structures — now it’s time to protect our code from breaking. Next up: Exceptions and Error Handling — we’ll throw, catch, and recover like pros.