How to Use the Final Keyword in Inheritance for Immutability

💡 The final Keyword in Inheritance: Ensuring Immutability 🔒 The final keyword in Java is a powerful tool for imposing limitations and ensuring immutability. When applied in the context of inheritance, it dictates how classes and methods can be extended or modified. 1. final Classes (No Inheritance) When you declare a class as final, it cannot be inherited by any other class. Syntax: public final class ParentClass { ... } Effect: You cannot create a subclass from it (e.g., you cannot say class ChildClass extends ParentClass). Use Case: Often used for security and integrity. Core Java classes like String and wrapper classes (e.g., Integer) are final to prevent their core behavior from being altered. 2. final Methods (No Overriding) When you declare a method as final in a parent class, that method cannot be overridden by any child class. Syntax: public final void calculateSalary() { ... } Effect: Any class inheriting from the parent must use the parent's exact implementation of that method. Use Case: Used to protect critical business logic or behavior that must remain consistent across the entire hierarchy, ensuring no subclass breaks the intended functionality. 3. final Variables (No Reassignment) While not strictly an inheritance rule, final variables are crucial to understand within objects. Effect: A final variable cannot be reassigned once it has been initialized. Use Case: Used to create constants (static final PI = 3.14) or ensure that an object's state (like an id) remains unchanged after the constructor runs. Mastering the final keyword is key to designing rigid, reliable, and secure class hierarchies. Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #OOP #ProgrammingTips #FinalKeyword #Inheritance #SoftwareDevelopment

  • diagram

To view or add a comment, sign in

Explore content categories