Skip to content

Commit 04ad549

Browse files
author
Ram swaroop
committed
added content
1 parent a874844 commit 04ad549

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

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

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,39 @@ inner class.
245245
Can |Cannot
246246
----------------|----------------
247247
Access private members of the outer/enclosing class. | Cannot use the local variables of the method the inner class is in.
248-
The only modifiers you can apply to a method-local inner class are abstract and final, but, as always, never both at the same time. | You can't mark a method-local inner class public, private, protected, static, transient (just like a variable).
248+
The only modifiers you can apply to a method-local inner class are `abstract` and `final`, but, as always, never both at the same time. | You can't mark a method-local inner class `public`, `private`, `protected`, `static` or `transient` (just like local variable declaration).
249+
250+
#### Important Points
251+
252+
* Method-local inner class __cannot access the local variables of the method inside which it is defined unless the
253+
variables are marked `final`__. This is because the local variables of the method live on the stack and exist only
254+
for the lifetime of the method. The scope of a local variable is limited to the method the variable is declared in.
255+
When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the
256+
inner class object created within it might still be alive on the heap if, for example, a reference to it was passed
257+
into some other code and then stored in an instance variable. Because the local variables aren't guaranteed to be alive
258+
as long as the method-local inner class object is, the inner class object can't use them. Unless the local variables
259+
are marked final.
260+
261+
{% highlight java linenos %}
262+
class MyOuter {
263+
private String x = "Outer";
264+
265+
void doStuff() {
266+
String z = "local variable";
267+
268+
class MyInner {
269+
public void seeOuter() {
270+
System.out.println("Outer x is " + x);
271+
System.out.println("Local var z is " + z); // won't compile, making 'z' final will solve the problem
272+
} // close inner class method
273+
} // close inner class definition
274+
} // close outer class method doStuff()
275+
} // close outer class
276+
{% endhighlight %}
277+
278+
* A local class declared in a `static` method has access to only `static` members of the enclosing class, since there is no
279+
associated instance of the enclosing class. If you're in a `static` method, there is no `this`, so an inner class in a
280+
`static` method is subject to the same restrictions as the `static` method. In other words, no access to instance variables.
249281

250282
251283

0 commit comments

Comments
 (0)