Nested और Inner Classes
Static nested class outer class के बिना भी independently use हो सकती है — सिर्फ़ Outer.Nested से access।
Inner (non-static) class outer object से जुड़ा होता है — उससे outer के instance members भी directly दिखते हैं।
Anonymous class एक नाम-less class है जो तुरंत, one-time use के लिए define की जाती है — जैसे एक button click listener।
class Outer {
static class Nested { void show() { System.out.println("Nested"); } }
class Inner { void show() { System.out.println("Inner"); } }
}- Static nested = independent helper class
- Inner = outer object से जुड़ा
- Anonymous = नाम-less, one-time use
Static nested class outer class के object के बिना भी बन सकती है — Outer.Nested obj = new Outer.Nested()। ये तब use होती है जब helper class का outer instance से कोई connection नहीं चाहिए, बस naming/grouping के लिए अंदर रखी है (जैसे Map.Entry, जो Map interface के अंदर static nested interface है)।
class Outer {
static class Nested {
void show() { System.out.println("Static nested!"); }
}
}
Outer.Nested n = new Outer.Nested(); // outer object nahi chahiyeNon-static inner class को बनाने के लिए पहले outer class का object चाहिए (outerObj.new Inner())। इसका फ़ायदा: inner class outer के सारे instance fields/methods directly access कर सकती है, बिना explicitly pass किए — क्योंकि inner class implicitly outer object की reference रखती है।
class Outer {
int x = 10;
class Inner {
void show() { System.out.println(x); } // outer ka x directly
}
}
Outer o = new Outer();
Outer.Inner i = o.new Inner(); // outer object zaroori haiMethod के अंदर ही एक class define कर सकते हो — "local class"। ये सिर्फ़ उसी method के अंदर use हो सकती है, और method के local (effectively final) variables को capture कर सकती है। Rare use-case है, लेकिन कभी-कभी एक complex helper logic को method के अंदर ही scope करना हो तब useful है।
बिना नाम के class जो तुरंत define और instantiate हो जाती है, one-time use के लिए — पुराने Java में event listeners इसी तरीक़े से लिखे जाते थे (Java 8 के lambda से पहले)। आज भी useful है जब एक interface/abstract class का सिर्फ़ एक-बार-use implementation चाहिए, और वो interface functional (एक method) नहीं है (जहाँ lambda काम नहीं करेगा)।
Runnable r = new Runnable() {
public void run() { System.out.println("Running!"); }
};