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

Why use enums?
- x>They give you a fixed set of allowed values.
- x>They're safer than strings or integers.
- x>You can even add methods and fields!

This helps enforce logic like:

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

That's a lot of code. With records:

That’s it. Java auto-generates:
- x>Constructor
- x>Getters (book.title())
- x>equals(), hashCode(), and toString()
When to use record:
- x>You’re modeling immutable data
- x>You need value semantics (they’re equal if their fields are equal)
When not to use it:
- x>If your class needs mutable fields or complex behavior
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.

Why use them?
- x>Restricts inheritance to specific classes
- x>Helps with exhaustive pattern matching (coming soon!)
- x>Makes your type hierarchies safer and easier to understand
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.
- x>Enums say “only these values”
- x>Records say “just data, don’t touch”
- x>Sealed classes say “inherit, but only like this”
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.