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

The final Keyword on Classes

Learn how declaring a class final prevents any subclass from extending it.

The final Keyword on Classes

You'll learn how to prevent a class from being extended by any subclass.


In the same way that final methods cannot be overridden, a final class cannot be extended. When you declare a class with the final keyword, you're saying "this class is complete as-is—no one can create a subclass from it."

Core Idea

The syntax is simple:

public final class MathConstants {
    // class body
}

Once MathConstants is marked final, any attempt to extend it will cause a compile-time error:

// This will NOT compile:
public class ExtendedMathConstants extends MathConstants {
    // Error: Cannot inherit from final MathConstants
}

Why Use final Classes?

Design intent: Some classes represent complete, immutable concepts that shouldn't be specialized. The String class in Java is final—you cannot create a custom subclass of String.

Security: Preventing subclassing ensures no one can override behavior in ways that might compromise the class's guarantees.

Optimization clarity: Though modern JVMs optimize well regardless, final clearly signals your design intention.

Analogy

Think of a final class like a sealed package that says "do not open, do not modify." It's a finished product—you can use it as-is, but you can't build a custom version by extending it.

When to Use It

Use final on classes when you want absolute control over behavior, when the class represents an unchangeable concept, or when inheritance would violate the class's contract.


Key Takeaway: Declaring a class final prevents any other class from extending it, ensuring the class's behavior remains exactly as you designed it.