Java Reference
In-Depth Information
Note that the syntax is not
OuterClass. new InnerClass();
This may seem like an apparent inconsistency with the syntax for creating the object
of a nonstatic inner class. It may help to keep in mind that for a static inner class,
OuterClass.InnerClass is a well-specified class name and all the information for
the object is in that class name. To remember the syntax for a nonstatic inner class,
remember that for that case, the object of the outer class modifies how the new operator
works to create an object of the inner class.
Once you have created an object of the inner class, the object can invoke a nonstatic
method in the usual way. For example,
innerObject.nonstaticMethod();
You can also use the object of the inner class to invoke a static method in the same
way. For example,
innerObject.staticMethod();
However, it is more common, and clearer, to use class names when invoking a static
method. For example,
OuterClass.InnerClass.staticMethod();
TIP: Referring to a Method of the Outer Class
As we have already noted, if a method is invoked in an inner class and the inner class
has no such method, then it is assumed to be an invocation of the method by that
name in the outer class. For example, we could add a method showBalance to the
inner class Money in Display 13.9, as outlined in what follows:
public class BankAccount
{
private class Money
{
private long dollars;
private int cents;
public void showBalance()
{
System.out.println(getBalance());
}
...
} //End of Money
(continued)
 
Search WWH ::




Custom Search