|
1 | 1 | --- |
2 | 2 | layout: post |
3 | | -title: Inner Classes |
| 3 | +title: Nested Classes |
4 | 4 | --- |
5 | 5 |
|
6 | | -A class inside another class is called an __Inner Class__. In other words, as a class has member variables and member |
7 | | -methods it can also have member classes. You can say inner classes are of 4 types: |
| 6 | +A class inside another class is called a __Nested Class__. In other words, as a class has member variables and member |
| 7 | +methods it can also have member classes. |
8 | 8 |
|
9 | | - * Inner classes |
| 9 | +Nested classes are divided into two categories: __static__ and __non-static__. Nested classes that are declared static |
| 10 | +are called __static nested classes__. Non-static nested classes are called __inner classes__. |
| 11 | + |
| 12 | +You can say inner classes are of 3 types: |
| 13 | + |
| 14 | + * "Regular" Inner classes |
10 | 15 | * Method-local inner classes |
11 | 16 | * Anonymous inner classes |
12 | | - * Static nested classes |
| 17 | + |
| 18 | +## Why Use Nested Classes? |
| 19 | + |
| 20 | + * __It is a way of logically grouping classes that are only used in one place__: If a class is useful to only one other |
| 21 | + class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes |
| 22 | + their package more streamlined. |
| 23 | + * __It increases encapsulation__: Consider two top-level classes, A and B, where B needs access to members of A that |
| 24 | + would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can |
| 25 | + access them. In addition, B itself can be hidden from the outside world. |
| 26 | + * __It can lead to more readable and maintainable code__: Nesting small classes within top-level classes places the |
| 27 | + code closer to where it is used. |
13 | 28 |
|
14 | 29 | ## Inner classes |
15 | 30 |
|
@@ -164,5 +179,9 @@ NOTE: Normally the inner class code doesn't need a reference to the outer class, |
164 | 179 | 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 |
165 | 180 | that reference to some other code as in the above example. |
166 | 181 |
|
| 182 | +## Method-Local Inner Classes |
| 183 | + |
| 184 | + |
| 185 | + |
167 | 186 |
|
168 | 187 |
|
0 commit comments