Static & Final

What are the keywords that change the very nature of your classes? Master Static, Final, and more to fine-tune your LLD.

April 26, 20264 min read13 / 14

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:

  1. Static (Shared): A static member belongs to the Class itself, not to any specific object. It is shared across all instances.
  2. 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.
  3. Memory Efficiency: Static members exist once in memory, rather than being copied for every object.
  4. Constants: We combine static and final to create global constants (e.g., Math.PI).

1. Static: The Shared Whiteboard

Instance Member

Every object gets its own copy. Changing one does not affect the others. Like a personal notebook.

class Student {
  name: string;
}

s1.name = "John";
s2.name = "Doe";

Values are unique to the "Instance."

Static Member

One shared copy for the whole class. Changing it updates the value for everyone. Like a whiteboard.

class Student {
  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.

  1. Final Variable: Once you set it, you can't change it. It's a Constant.
  2. Final Method: You like your code so much you don't want any child to override it.
  3. Final Class: You want to stop the family tree here. No one can extends a final class.
const PI = 3.14159; // In TS/JS, we use 'const'

When to Use Which?

  1. Use Static for Utilities: Methods that don't need object data (like Math.sqrt()) should be static.
  2. Use Final for Security: If you have a sensitive checkPassword method, mark it final so 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.

Static: The Global Counter
1 exercise