Static & Final
What are the keywords that change the very nature of your classes? Master Static, Final, and more to fine-tune your LLD.
Beyond the pillars of OOP, there are special keywords that act as "modifiers" for your classes and members. Two of the most important are Static and Final.
The Essentials
The "Fine Print" guide:
- Static (Shared): A static member belongs to the Class itself, not to any specific object. It is shared across all instances.
- Final (Locked): A final member cannot be changed. For a class, it means no inheritance; for a method, no overriding; for a variable, no reassignment.
- Memory Efficiency: Static members exist once in memory, rather than being copied for every object.
- Constants: We combine
staticandfinalto create global constants (e.g.,Math.PI).
1. Static: The Shared Whiteboard
Every object gets its own copy. Changing one does not affect the others. Like a personal notebook.
name: string;
}
s1.name = "John";
s2.name = "Doe";
Values are unique to the "Instance."
One shared copy for the whole class. Changing it updates the value for everyone. Like a whiteboard.
static school = "Academy";
}
Student.school = "New Univ";
The value is unique to the "Class."
Code Implementation: Static vs. Final
Here is how these keywords change the behavior of your members:
class PhysicsConstants {
// Static: Belongs to the class, not the object
static schoolName: string = "Durgesh.dev Academy";
// Final (const in TS): Cannot be reassigned
readonly gravity: number = 9.8;
}
// Access static without 'new'
console.log(PhysicsConstants.schoolName);2. Final: The Dead End
The final keyword is about Finality.
- Final Variable: Once you set it, you can't change it. It's a Constant.
- Final Method: You like your code so much you don't want any child to override it.
- Final Class: You want to stop the family tree here. No one can
extendsa final class.
const PI = 3.14159; // In TS/JS, we use 'const'When to Use Which?
- Use Static for Utilities: Methods that don't need object data (like
Math.sqrt()) should be static. - Use Final for Security: If you have a sensitive
checkPasswordmethod, mark itfinalso no one can override it with a "return true" hack.
By mastering these modifiers, you add a layer of precision and safety to your designs, ensuring your code behaves exactly as intended.
Finally, let's explore a subtle but important topic: Shadowing and Hiding.
Practice what you just read.