Java Reference
In-Depth Information
EXAMPLE: (continued)
The class Money is a private inner class of the class BankAccount . So, the class Money
cannot be used outside of the class BankAccount . (Public inner classes are discussed in
Section 13.3 and have some subtleties involved in their use.) Since the class Money is
local to the class BankAccount , the name Money can be used for the name of another
class outside of the class BankAccount . (This would be true even if Money were a public
inner class.)
We have made the instance variables in the class Money private following our usual
conventions for class members. When we discuss public inner classes, this will be
important. However, for use within the outer class (and a private inner class cannot be
used anyplace else), there is no difference between public and private or other mem-
ber modifiers. All instance variables and all methods of the inner class are public to the
outer class no matter whether they are marked public or private or anything else.
Notice the method closeAccount of the outer class. It uses the private instance vari-
ables dollars and cents of the inner class.
This is still very much a toy example, but we will have occasion to make serious use
of private inner classes when we discuss linked lists in Chapter 15 and when we study
Swing GUIs starting in Chapter 17.
Display 13.9 Class with an Inner Class (part 1 of 2)
1 public class BankAccount
2{
3
private class Money
The modifier private in this line
should not be changed to public .
However, the modifiers public and
private inside the inner class Money
can be changed to anything else and
it would have no effect on the class
BankAccount .
4
{
5
private long dollars;
6
private int cents;
7
public Money(String stringAmount)
8
{
9
abortOnNull(stringAmount);
10
int length = stringAmount.length();
11
dollars = Long.parseLong(
3));
12
stringAmount.substring(0, length
13
cents = Integer.parseInt(
2, length));
14
stringAmount.substring(length
15
}
16
public String getAmount()
17
{
18
if (cents > 9)
 
Search WWH ::




Custom Search