Java Reference
In-Depth Information
Helping Inner Classes
You may define a class within another class. The inside class is called an
inner class
. A com-
mon and simple use of an inner class is to use it as a helping class for the outer class, in
which case the inner class should be marked
private
.
Self-Test Exercises
20. Would the following invocation of
getAmount
in the method
getBalance
of the
outer class
BankAccount
still be legal if we change the method
getAmount
of
the inner class
Money
from
public
to
private
?
public
String getBalance()
{
return
balance.getAmount();
}
21. Since it does not matter if we make the members of a private inner class public or
private, can we simply omit the
public
or
private
modifiers from the instance
variables and methods of a private inner class?
22. Would it be legal to add the following method to the inner class
Money
in Display
13.9? Remember, the question is would it be legal, not would it be sensible.
public void
doubleBalance()
{
balance.addIn(balance);
}
23. Would it be legal to add the following method to the inner class
Money
in Display
13.9? Remember, the question is would it be legal, not would it be sensible.
public void
doubleBalance2()
{
makeDeposit(balance.getAmount());
}
The
.class
File for an Inner Class
When you compile any class in Java, that produces a
.class
file. When you compile a
class with an inner class, that compiles both the outer class and the inner class and pro-
duces two
.class
files. For example, when you compile the class
BankAccount
in Dis-
play 13.9, that produces the following two
.class
files:
BankAccount.class
and
BankAccount$Money.class
If
BankAccount
had two inner classes, then three
.class
files would be produced.