Skip to content

Commit 3719d85

Browse files
author
Ram swaroop
committed
inner class instantiation added
1 parent 6199025 commit 3719d85

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

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

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public class MyOuter {
3131
When you compile it :
3232

3333
{% highlight java %}
34-
`javac MyOuter.java`
34+
javac MyOuter.java
3535
{% endhighlight %}
3636

3737
you will end up with two class files:
@@ -74,6 +74,27 @@ the same.
7474

7575
### Instantiate the inner class
7676

77+
To create an instance of an inner class, you must have an instance of the outer class to tie to the inner class. There
78+
are no exceptions to this rule: __An inner class instance can never stand alone without a direct relationship to an
79+
instance of the outer class__.
80+
81+
{% highlight java linenos %}
82+
public class MyOuter {
83+
private int x = 7;
84+
85+
public void makeInner() {
86+
MyInner in = new MyInner(); // make an inner instance
87+
in.seeOuter();
88+
}
89+
90+
class MyInner {
91+
public void seeOuter() {
92+
System.out.println("Outer x is " + x);
93+
}
94+
}
95+
}
96+
{% endhighlight %}
97+
7798

7899

79100

0 commit comments

Comments
 (0)