this और static keyword
this current object को refer करता है — जब parameter और field का नाम same हो, तब confusion दूर करता है।
static member class का होता है, किसी एक object का नहीं — सब objects उसको share करते हैं, जैसे एक common counter।
class Counter {
static int total = 0;
Counter() { total++; }
}- this = अपना current object
- static = class के साथ shared
- Object के बिना भी ClassName.member
this() call एक constructor से दूसरे constructor (same class के) को चलाता है — इससे repeated initialization code लिखने से बचते हैं। पूरा detail Constructor topic में है, लेकिन याद रखने वाली बात: this() हमेशा constructor की पहली line होनी चाहिए।
Static variable class-level होता है, object-level नहीं — ये class के साथ एक ही बार memory में exist करता है (चाहे 1 object बनो या 1000)। Classic use-case: एक counter जो track करे कितने objects अभी तक बने — हर object बनते वक़्त (constructor में) ये counter बढ़ाया जाता है, और सब objects उसी एक shared value को देखते हैं।
Static variables class load होते ही (JVM के अंदर) बनते हैं, object बनाए बिना भी access हो सकते हैं — ClassName.variableName से।
class User {
static int totalUsers = 0;
User() { totalUsers++; }
}
new User(); new User(); new User();
System.out.println(User.totalUsers); // 3Static methods object बनाए बिना directly ClassName.methodName() से call होते हैं — Math.max(), Math.sqrt(), Integer.parseInt() classic examples हैं। पूरी "Math" class ही static methods से भरी है क्योंकि maths operations को किसी specific object state की ज़रूरत नहीं होती।
Static method के अंदर सिर्फ़ static members ही *directly* access हो सकते हैं (क्योंकि "this" का कोई मतलब नहीं होता बिना object के — JVM को पता ही नहीं कौनसा object)। अगर instance member चाहिए, एक object explicitly बनाना/pass करना पड़ेगा।
static { } block class load होते ही एक बार चलता है — object बनने से भी पहले, program के बिल्कुल शुरू में (जब JVM पहली बार उस class को use करता है)। ये complex static variables initialize करने के लिए use होता है जिन्हें simple assignment से initialize नहीं कर सकते (जैसे file से config पढ़ना, या multiple lines की logic चाहिए)।
एक class में multiple static blocks भी हो सकते हैं — वो declaration order में, top-से-bottom चलते हैं।
class Config {
static String env;
static {
env = loadFromFile(); // complex setup, ek baar hi hota hai
System.out.println("Config loaded!");
}
}