A final class in Java is a class that cannot be extended (inherited). By declaring a class as final
, you prevent other classes from subclassing it, ensuring its behavior remains unchanged. In this guide, you’ll learn how to use final classes, their benefits, and practical examples to secure your code.
Table of Contents
What is a Final Class in Java?
A final class is declared using the final
keyword:
public final class String { // java.lang.String is a final class
// Class implementation
}
Key Characteristics:
- Cannot be subclassed: Any attempt to
extend
it causes a compile-time error. - Methods are implicitly final: Cannot be overridden (since the class itself can’t be extended).
Why Use a Final Class?
- Security: Prevent malicious or accidental subclassing (e.g., overriding methods to alter behavior).
- Immutability: Ensure critical classes like
String
remain unmodifiable. - API Design: Lock down class behavior in libraries/frameworks.
- Performance: Some JVM optimizations apply to final classes.
Example: Declaring and Using a Final Class
1. Define a Final Class
public final class Logger {
public void log(String message) {
System.out.println("[LOG] " + message);
}
}
2. Attempting to Extend (Error)
// Compiler Error: Cannot inherit from final Logger
class CustomLogger extends Logger {
// ❌ Not allowed!
}
Final Class vs. Final Method vs. Final Variable
Keyword | Applies To | Effect |
---|---|---|
Final Class | Class declaration | Prevents inheritance. |
Final Method | Method in a class | Prevents overriding in subclasses. |
Final Variable | Variable (field/local) | Makes the variable a constant (unmodifiable). |
Best Practices
- Use Sparingly: Finalize only classes critical to security/immutability.
- Combine with Private Constructors: For utility classes (prevent instantiation).
- Document Reasons: Clarify why a class is final (e.g., “Security: prevent tampering”).
- Consider Alternatives: Use encapsulation or interfaces if extensibility is needed.
Conclusion
Final class in Java are essential for designing secure, immutable, and stable APIs. By preventing inheritance, they safeguard critical logic from unintended modifications. Use them judiciously to balance flexibility and control.
FAQs
Can a final class be abstract?
No. final
and abstract
are contradictory (abstract classes require subclassing).
Can a final class have methods?
Yes, but they can’t be overridden since the class can’t be extended.
Is the String
class really final?
Yes. java.lang.String
is final to ensure immutability and security.
Can a final class implement an interface?
Yes. Implementing an interface doesn’t require inheritance.