|
An instance of a member inner class can never be created without an instance of the outer class. Instance methods of a class can refer to its instance (on which they were invoked) using the this keyword. Thus, instance methods always have an access to the current enclosing instance. Therefore, you can create an instance of member inner class inside instance methods without any need to create the enclosing instance. Listing 4.1 illustrates the instance creation of a member inner class InnerOne inside an instance method.

Though it appears that method createInstance() is directly creating an instance of the member inner class, it is implicitly doing so on the current instance of OuterOne. Note that the createInstance() is an instance method, hence it will always be called on some instance of OuterOne. This instance is implicitly available within that instance method and you can explicitly refer it with this keyword. For example, the createInstance() method in listing 4.1 is actually creating instance as:
public void createInstance() {
InnerOne inner = this.new InnerOne();
inner.displayMessage();
}
The static methods do not have access to this object. Hence, static methods cannot directly create an instance of member inner class. They have to create an instance of the enclosing class first.