🔗
OOP

this & static keyword

Self vs Shared
💡 "this" means "myself" — it points to your own field. "static" is like a shared locker that all objects use together.

this refers to the current object — it clears up confusion when a parameter and a field share the same name.

A static member belongs to the class, not to any one object — all objects share it, like a common counter.

class Counter {
  static int total = 0;
  Counter() { total++; }
}
🔗
"this" means "myself" — it points to your own field. "static" is like a shared locker that all objects use together.
1 / 4
On this page (4 subtopics)

this() call ek constructor se dusre constructor (same class ke) ko chalata hai — isse repeated initialization code likhne se bachte hain. Poora detail Constructor topic mein hai, lekin yaad rakhne wali baat: this() hamesha constructor ki pehli line honi chahiye.

Static variable class-level hota hai, object-level nahi — ye class ke saath ek hi baar memory mein exist karta hai (chahe 1 object bano ya 1000). Classic use-case: ek counter jo track kare kitne objects abhi tak bane — har object banते waqt (constructor mein) ye counter badhaya jaata hai, aur sab objects usi ek shared value ko dekhte hain.

Static variables class load hote hi (JVM ke andar) bante hain, object banaye bina bhi access ho sakte hain — ClassName.variableName se.

class User {
  static int totalUsers = 0;
  User() { totalUsers++; }
}
new User(); new User(); new User();
System.out.println(User.totalUsers); // 3

Static methods object banaye bina directly ClassName.methodName() se call hote hain — Math.max(), Math.sqrt(), Integer.parseInt() classic examples hain. Puri "Math" class hi static methods se bhari hai kyunki maths operations ko kisi specific object state ki zaroorat nahi hoti.

Static method ke andar sirf static members hi *directly* access ho sakte hain (kyunki "this" ka koi matlab nahi hota bina object ke — JVM ko pata hi nahi kaunsa object). Agar instance member chahiye, ek object explicitly banana/pass karna padega.

⚠️Common Mistake: Static method ke andar non-static (instance) field/method access karne ki koshish karoge to compile error milega: "non-static variable cannot be referenced from a static context".

static { } block class load hote hi ek baar chalta hai — object banने se bhi pehle, program ke bilkul shuru mein (jab JVM pehli baar us class ko use karta hai). Ye complex static variables initialize karne ke liye use hota hai jinhe simple assignment se initialize nahi kar sakte (jaise file se config padhna, ya multiple lines ki logic chahiye).

Ek class mein multiple static blocks bhi ho sakte hain — wo declaration order mein, top-se-bottom chalte hain.

class Config {
  static String env;
  static {
    env = loadFromFile(); // complex setup, ek baar hi hota hai
    System.out.println("Config loaded!");
  }
}