Skip to content

Commit aa91ded

Browse files
author
Ram swaroop
committed
added content
1 parent f8d0076 commit aa91ded

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

_posts/2015-08-20-nested-classes.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,63 @@ that reference to some other code as in the above example.
181181

182182
## Method-Local Inner Classes
183183

184+
A regular inner class scoped inside another class's curly braces, but outside any method code (in other words, at the
185+
same level that an instance variable is declared) is called a __method-local inner class__.
186+
187+
{% highlight java linenos %}
188+
class Outer {
189+
190+
private String x = "Outer";
191+
192+
void doStuff() {
193+
194+
class Inner {
195+
196+
public void seeOuter() {
197+
System.out.println("Outer x is " + x);
198+
} // close inner class method
199+
200+
} // close inner class definition
201+
202+
} // close outer class method doStuff()
203+
204+
} // close outer class
205+
{% endhighlight %}
206+
207+
In the above example, `class Inner` is the method-local inner class. But the inner class is useless because you are never
208+
instantiating the inner class. Just because you declared the class doesn't mean you created an instance of it. So to
209+
use the inner class, you must make an instance of it somewhere within the method but __below the inner class definition
210+
(or the compiler won't be able to find the inner class)__.
211+
212+
The following legal code shows how to instantiate and use a method-local inner class:
213+
214+
{% highlight java linenos %}
215+
class Outer {
216+
217+
private String x = "Outer";
218+
219+
void doStuff() {
220+
221+
class Inner {
222+
223+
public void seeOuter() {
224+
System.out.println("Outer x is " + x);
225+
} // close inner class method
226+
227+
MyInner mi = new MyInner(); // This line must come
228+
// after the class
229+
230+
mi.seeOuter();
231+
232+
} // close inner class definition
233+
234+
} // close outer class method doStuff()
235+
236+
} // close outer class
237+
{% endhighlight %}
238+
239+
### What a Method-Local Inner Object Can and Can't Do
240+
184241

185242

186243

0 commit comments

Comments
 (0)