πŸ”Ή The final Keyword in OOP

The final keyword is used in Object-Oriented Programming (OOP) to **restrict modifications** to classes, methods, and variables. It helps enforce **immutability, security, and better design practices**.

πŸ“Œ Why Use the final Keyword?

The final keyword ensures that certain parts of the code **cannot be changed** after they are defined.

  • βœ… **Prevents Accidental Modifications** – Ensures code stability.
  • βœ… **Improves Security** – Restricts unauthorized method overriding.
  • βœ… **Enhances Performance** – Allows compiler optimizations.
  • βœ… **Supports Immutability** – Helps in creating constant variables.

πŸ“Œ Usage of final Keyword

πŸ”Ή 1. final Variables (Constants)

Variables declared with final **cannot be reassigned** after initialization.


            class MathConstants {
                final double PI = 3.14159;  // βœ… Constant value
            
                void show() {
                    // PI = 3.14; ❌ ERROR: Cannot modify final variable
                    System.out.println("PI value: " + PI);
                }
            }
                

πŸ”Ή 2. final Methods (Prevent Overriding)

Methods marked with final **cannot be overridden** in subclasses.


            class Parent {
                final void showMessage() {
                    System.out.println("This method cannot be overridden.");
                }
            }
            
            class Child extends Parent {
                // void showMessage() { ❌ ERROR: Cannot override final method
                //     System.out.println("Trying to override.");
                // }
            }
                

πŸ”Ή 3. final Classes (Prevent Inheritance)

Classes marked with final **cannot be extended (inherited)**.


            final class SecureClass {
                void display() {
                    System.out.println("This class cannot be extended.");
                }
            }
            
            // class HackerClass extends SecureClass { ❌ ERROR: Cannot inherit final class
            // }
                

πŸ“Œ When to Use final?

  • βœ… Use final variables to define **constants** (e.g., PI, tax rates).
  • βœ… Use final methods when you don’t want subclasses to **override critical behavior**.
  • βœ… Use final classes when you want to **prevent inheritance** (e.g., security-sensitive classes).

🎯 Summary

The final keyword **restricts modifications** to variables, methods, and classes. It ensures **security, stability, and performance optimization** in OOP.

πŸ”— Next Topics