@@ -79,4 +79,77 @@ public enum Seasons {
79
79
abstract void printHours ();
80
80
}
81
81
```
82
- * We can also remove the ` abstract ` modifier so that all of the enums will use a default implementation.
82
+ * We can also remove the ` abstract ` modifier so that all of the enums will use a default implementation.
83
+
84
+ <hr >
85
+
86
+ # 🧠 1.5 Creating Nested Classes
87
+
88
+ ## 🟥 Member Inner Classes
89
+ * A member inner class can have any access modifier, it can extend any class/interface (including other inner classes)
90
+ * Can be abstract or final, they can not contain static members
91
+ * They CAN access enclosing class's members (even private ones)
92
+ ``` java
93
+ public class Outer {
94
+ private String greeting = " hi" ;
95
+ private class Inner {
96
+ public void go () {
97
+ for (int i= 0 ;i< 3 ;i++ )
98
+ System . out. println(greeting);
99
+ }
100
+ }
101
+ void callInner () {
102
+ Inner inner = new Inner ();
103
+ }
104
+ public static void main (String [] args ) {
105
+ // Inner inner = new Inner(); // COMPILER ERROR
106
+ new Outer (). callInner();;
107
+ }
108
+ }
109
+ public class Outer {
110
+ private String greeting = " hi" ;
111
+ private class Inner {
112
+ public void go () {
113
+ for (int i= 0 ;i< 3 ;i++ )
114
+ System . out. println(greeting);
115
+ }
116
+ }
117
+ void callInner () {
118
+ Inner inner = new Inner ();
119
+ }
120
+ public static void main (String [] args ) {
121
+ // Inner inner = new Inner(); // COMPILER ERROR
122
+ new Outer (). callInner();
123
+ Inner inner = new Outer (). new Inner ();
124
+ }
125
+ }
126
+ ```
127
+
128
+ <br >
129
+
130
+ * The inner class can have the same variable names as outside:
131
+
132
+ ``` java
133
+ public class A {
134
+ int x = 11 ;
135
+ class B {
136
+ int x = 22 ;
137
+ class C {
138
+ int x = 33 ;
139
+ int y = 456 ;
140
+ void printAll () {
141
+ System . out. println(x); // 33
142
+ System . out. println(this . x); // 33
143
+ System . out. println(B . this . x); // 22
144
+ System . out. println(A . this . x); // 11
145
+ }
146
+ }
147
+ }
148
+ public static void main (String [] args ) {
149
+ int aX = new A (). x;
150
+ int bX = new A (). new B (). x;
151
+ int cX = new A (). new B (). new C (). x;
152
+ new A (). new B (). new C (). printAll();
153
+ }
154
+ }
155
+ ```
0 commit comments