Skip to content

Commit bbf1730

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

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

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

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,9 @@ methods it can also have member classes. You can say inner classes are of 4 type
1111
* Anonymous inner classes
1212
* Static nested classes
1313

14-
### When it is good to have an inner class?
15-
16-
Let's say you have to design a chat client in java through which a user can send messages to the server.
17-
chat-client–specific methods (accept input, read new messages from server, send user input back to server, and so on) to
18-
be in the class
14+
## Inner classes
1915

16+
These are just "regular" inner classes which are not method-local, anonymous or static.
2017

2118
### Little Basics
2219

@@ -28,7 +25,7 @@ public class MyOuter {
2825
}
2926
{% endhighlight %}
3027

31-
When you compile it :
28+
When you compile it:
3229

3330
{% highlight java %}
3431
javac MyOuter.java
@@ -97,16 +94,36 @@ public class MyOuter {
9794
}
9895
{% endhighlight %}
9996

97+
The reason the above syntax works is because the outer class instance method code is doing the instantiating. In other
98+
words, there's already an instance of the outer class—the instance running the makeInner() method.
99+
100100
#### Instantiating an Inner Class from Outside the Outer Class Instance Code
101101

102102
{% highlight java %}
103103
public static void main(String[] args) {
104-
MyOuter mo = new MyOuter(); // gotta get an instance!
105-
MyOuter.MyInner inner = mo.new MyInner();
104+
MyOuter mo = new MyOuter(); // gotta get an instance of outer class
105+
MyOuter.MyInner inner = mo.new MyInner(); // instantiate inner class from outer class instance
106106
inner.seeOuter();
107107
}
108108
{% endhighlight %}
109109

110+
As we know that we must have an outer class instance to create an inner class instance, the above code would be the way
111+
to go. _Instantiating an inner class is the only scenario in which you'll invoke new on an instance as opposed to invoking
112+
new to construct an instance._
113+
114+
If you are a one liner then the below code is for you:
115+
116+
{% highlight java %}
117+
public static void main(String[] args) {
118+
MyOuter.MyInner inner = new MyOuter().new MyInner(); // all in one line
119+
inner.seeOuter();
120+
}
121+
{% endhighlight %}
122+
123+
#### Referencing the Inner or Outer Instance from Within the Inner Class
124+
125+
126+
110127

111128

112129

0 commit comments

Comments
 (0)