Use Cases for final Classes
You'll learn: When and why marking a class as final makes sense in real-world Java development.
Now that you know how to make a class final, let's explore why you'd actually want to.
Immutability Guarantees
When you create an immutable class (one whose state cannot change after construction), marking it final protects that design. If someone could extend your immutable class, they might add mutable fields, breaking your carefully designed immutability contract.
Analogy: Think of a sealed envelope. Making the class final prevents anyone from adding extra pockets where they could stuff changeable notes.
public final class Money {
private final int dollars;
private final int cents;
public Money(int dollars, int cents) {
this.dollars = dollars;
this.cents = cents;
}
public int getDollars() { return dollars; }
public int getCents() { return cents; }
}
Nobody can extend Money and add a setDollars() method that would violate immutability.
Security
Classes handling sensitive operations (authentication, cryptography) are often marked final to prevent malicious subclasses from overriding methods with unsafe behavior.
API Design Clarity
When you make a class final, you're telling other developers: "This class is complete and ready to use as-is—compose with it rather than extend it." This simplifies your API's contract and future maintenance.
Real example: Java's String class is final. This guarantees predictable behavior everywhere strings are used and enables optimizations like string interning.
Key Takeaway: Use final on classes when you need immutability guarantees, security protection, or want to clearly signal that a class is not designed for inheritance.