Skip to content

Commit 8539877

Browse files
author
Ram swaroop
committed
added content
1 parent bbf1730 commit 8539877

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

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

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,33 @@ public static void main(String[] args) {
122122

123123
#### Referencing the Inner or Outer Instance from Within the Inner Class
124124

125+
An object refers to itself normally by using the `this` reference. The `this` reference is the way an object can pass a
126+
reference to itself to some other code as a method argument:
125127

128+
{% highlight java %}
129+
public void myMethod() {
130+
MyClass mc = new MyClass();
131+
mc.doStuff(this); // pass a ref to object running myMethod
132+
}
133+
{% endhighlight %}
134+
135+
So within an inner class code, the `this` reference refers to the instance of the inner class, as you'd probably expect,
136+
since `this` always refers to the currently executing object. But when the inner class code wants an explicit reference
137+
to the outer class instance that the inner instance is tied to, it can access the outer class `this` like:
138+
139+
{% highlight java %}
140+
class MyInner {
141+
public void seeOuter() {
142+
System.out.println("Outer x is " + x);
143+
System.out.println("Inner class ref is " + this);
144+
System.out.println("Outer class ref is " + MyOuter.this);
145+
}
146+
}
147+
{% endhighlight %}
126148

149+
NOTE: Normally the inner class code doesn't need a reference to the outer class, since it already has an implicit one
150+
it's using to access the members of the outer class, it would need a reference to the outer class if it needed to pass
151+
that reference to some other code as in the above example.
127152

128153

129154

0 commit comments

Comments
 (0)