Course contentsShow
← Java
Lesson 431 of 2,87010. Inheritance FundamentalsFree lesson

Design Decisions: When to Use final

Learn guidelines for choosing final: favoring composition, immutability, and open vs closed class hierarchies.

Design Decisions: When to Use final

You'll learn practical guidelines for deciding when applying final to classes and methods strengthens your design.

Now that you understand what final does technically, the real question is: when should you actually use it? The answer lies in understanding your design goals and the trade-offs between flexibility and constraints.

Guidelines for Using final

Favor Composition Over Inheritance

If you find yourself making a class final, ask: should this even be inherited from, or should other classes contain it instead? Sometimes marking a class final is a signal that composition (having it as a field) is the better relationship.

Immutability and Safety

Use final classes when creating immutable types (like String or wrapper classes). Preventing subclassing ensures no one can add mutable state or break your carefully designed immutability contract.

Open vs Closed Class Hierarchies

Open hierarchies (without final) invite extension—think frameworks where users create custom subclasses. Use this when you want flexibility.

Closed hierarchies (with final) enforce boundaries—think String or Integer. Use this when your implementation is complete and shouldn't be altered, or when security/correctness depends on specific behavior.

When NOT to Use final

Don't make things final "just because." Premature finalization limits future testing (can't mock final classes easily) and adaptation. Only apply final when you have a clear design reason.

The Mindset

Think of final as a contract with users of your code: "This is complete as-is; build around it, not from it." Use it deliberately, not defensively.

Key Takeaway: Use final when you need immutability guarantees or want to enforce a closed design; prefer composition over inheritance when possible, and keep hierarchies open unless you have a specific reason to close them.