Java Reference
In-Depth Information
TIP: Inner and Outer Classes Have Access to Each Other's
Private Members
Within the defi nition of a method of an inner class, it is legal to reference a private
instance variable of the outer class and to invoke a private method of the outer class.
To facilitate this, Java follows this convention: 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. (If the outer class also has no method by that
name, that is, of course, an error.) Similarly, an inner class can use the name of an
instance variable of the outer class.
The reverse situation, invoking a method of the inner class from the outer class, is
not so simple. To invoke a (nonstatic) method of the inner class from within a method
of the outer class, you need an object of the inner class to use as a calling object, as we
do in Display 13.9 .
As long as you are within the defi nition of the inner or outer classes, the modifi ers
public and private (used within the inner or outer classes) are equivalent.
These sorts of invocations and variable references that cross between inner and outer
classes can get confusing. So, it is best to confi ne such invocations and variable refer-
ences to cases that are clear and straightforward. It is easy to tie your code in knots if
you get carried away with this sort of thing.
Access Privileges between Inner and Outer Classes
Inner and outer classes have access to each other's private members.
EXAMPLE: A Bank Account Class
Display 13.9 contains a simplified bank account program with an inner class for
amounts of money. The bank account class uses values of type String to obtain or
return amounts of money, such as the amount of a deposit or the answer to a query for
the account balance. However, inside the class it stores amounts of money as values of
type Money , which is an inner class. Values of type Money are not stored as String s,
which would be difficult to do arithmetic on, nor are they stored as values of type
double , which would allow round-off errors that would not be acceptable in banking
transactions. Instead, the class Money stores amounts of money as two integers, one
for the dollars and one for the cents. In a real banking program, the class Money might
have a larger collection of methods, such as methods to do addition, subtraction, and
compute percentages, but in this simple example we included only the method for
adding an amount of money to the calling object. The outer class BankAccount would
also have more methods in a real class, but here we included only methods to deposit
an amount of money to the account and to obtain the account balance. Display 13.10
contains a simple demonstration program using the class BankAccount .
(continued)
 
Search WWH ::




Custom Search