Immutability and final: Defensive Access Control
You'll learn how combining private access with final fields creates rock-solid, predictable classes.
The Core Idea
Access control isn't just about hiding fields—it's about guaranteeing behavior. When you mark fields as both private and final, you create immutable state: data that cannot change after object construction. This is defensive programming at its best.
Think of it like a locked safe with the combination written inside during manufacturing, then sealed forever. No one can open it to change the combination—they can only read what's visible through the window (your public methods).
Why Combine private and final?
privateprevents external access: other classes can't touch your fieldsfinalprevents internal modification: even your own class can't reassign the field after construction- Together, they guarantee the object's state never changes
public class User {
private final String username; // locked at construction
private final int userId;
public User(String username, int userId) {
this.username = username;
this.userId = userId;
}
public String getUsername() {
return username; // safe to return—it can't be changed
}
public int getUserId() {
return userId;
}
}
Once a User object is created, its username and userId cannot be modified by anyone—not external code, not even methods inside User. This makes the class thread-safe (multiple threads can safely share the object) and predictable (no surprising state changes).
Benefits of This Pattern
- Thread safety without synchronization: immutable objects are inherently safe to share
- Easier reasoning: the object's state at construction is its state forever
- Prevents accidental bugs: no setter methods means no one can corrupt your data
Key Takeaway: Combining private access with final fields creates immutable, trustworthy objects that resist misuse and eliminate entire categories of bugs—the ultimate defensive access control strategy.