Final keyword in Inheritance
In Java, the final
keyword plays an important role in controlling inheritance and method overriding. Here's a detailed explanation.
🔐 final
Keyword in Inheritance
The final
keyword can be applied to:
Usage | Purpose |
---|---|
final class | Prevents a class from being subclassed |
final method | Prevents a method from being overridden |
final variable | Prevents a variable from being reassigned |
final
helps to restrict changes to a class or method.📌 1. final
Class
A final
class cannot be extended. You use it when you want to stop inheritance completely.
✅ Example:
📌 2. final
Method
A final
method cannot be overridden in any subclass. You use it when you want to prevent overriding, for example, for security or consistency.
✅ Example:
🧠 Use Cases:
-
Prevent overriding of sensitive logic
-
Prevent subclass from changing inherited behavior
🧠 Why Use final
in Inheritance?
-
Security: Prevent altering critical methods
-
Optimization: Java compiler may optimize calls to
final
methods -
Design Integrity: Enforce that some classes/methods remain unchanged
❌ What You Cannot Do with final
in Inheritance
Action | Allowed? | Reason |
---|---|---|
Extend a final class | ❌ | Final class is sealed |
Override a final method | ❌ | Final methods are locked |
Modify a final variable | ❌ | Final variables are constants |
✅ Summary
final Applied To | Effect in Inheritance |
---|---|
Class | Cannot be extended |
Method | Cannot be overridden |
Variable | Not related to inheritance, but value-fixed |
Comments
Post a Comment