|
When we say that an inner class is accessible to a certain class, it means that the class can create an instance of that inner class. Like other instance members, the member inner class cannot exist without an instance of enclosing class. For example, you cannot instantiate the member inner class InnerOne, like this:
new OuterOne.InnerOne(); // Compiler Error
You need to create an instance of the enclosing class first. Let us instantiate InnerOne by first creating the enclosing instance of OuterOne. Figure 4.1 illustrates the instantiation of InnerOne.

Figure 4.1 Instantiation of a member inner class InnerOne
An instance of a member inner class InnerOne is created on the second line. The syntax is a bit unusual. The new keyword is used on the reference of OuterOne instance, outer. The object reference can be used in this way only while instantiating an inner class.
|
|
In the example we discussed, InnerOne is referred as OuterOne.InnerOne within Java code. However, filename for InnerOne is OuterOne$InnerOne.class on the storage media. Therefore the filename is ‘OuterOne$InnerOne’ for the class loader. Hence if you try to get the Class instance of inner class using the Class.forName()[*******] static method, then Class.forName(“OuterOne$InnerOne”) works fine. Note that Class.forName(“OuterOne.InnerOne”) will not work as there is no file named OuterOne.InnerOne. |
The member inner class can also be instantiated in one line. Figure 4.2 illustrates how you can instantiate InnerOne using the instance of enclosing class in a single line of code.

Figure 4.2 Instantiation of a member inner class InnerOne in oneline
The class InnerOne can be instantiated from any class that can access both, the OuterOne and the InnerOne class. In our example, all classes will have an access to OuterOne as it is a public class. But since the class InnerOne is declared as protected, only classes in the package com.example.scjp.studykit and subclasses of OuterOne will have an access to the protected class InnerOne. Therefore effectively only classes that can access InnerOne can create an instance of it.
|
|
Access modifiers control the accessibility of member classes in similar manner it controls the accessibility of member variables and methods of class. For example, the accessibility of private member class and private variable is same. A private variable is accessible within a class and a private non-static member class can only be instantiated within the enclosing class. |