πΉ 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.