Java Reference
In-Depth Information
In this case we bind the second
Action
object to the
otherBankAccount
ob-
ject and store it as the last action of the other account. Each
BankAccount
object should only refer to
Action
objects for which that
BankAccount
ob-
ject is the enclosing instance. It would make no sense above, for ex-
ample, to store the same
Action
object in both the current
lastAct
field
and
other.lastAct
.
An inner class declaration is just like a top-level class declaration except
for one restrictioninner classes cannot have static members (including
static nested types), except for final static fields that are initialized to
constants or expressions built up from constants. The rationale for al-
lowing constants to be declared in an inner class is the same as that
for allowing them in interfacesit can be convenient to define constants
within the type that uses them.
As with top-level classes, inner classes can extend any other classin-
by any other class. An inner class can be declared
final
or
abstract
, and
can have annotations applied to it.
[2]
It is hard to think of a reason why you would want to do this, and easy to get a headache reasoning
about what it means.
Exercise 5.2
: Create a version of
BankAccount
that records the last ten
actions on the account. Add a
history
method that returns a
History
ob-
ject that will return
Action
objects one at a time via a
next
method, re-
turning
null
at the end of the list. Should
History
be a nested class? If
so, should it be static or not?
5.2.1. Accessing Enclosing Objects
The
toString
method of
Action
directly uses the
number
field of its en-
closing
BankAccount
object. A nested class can access all members of its
enclosing classincluding private fields and methodswithout qualification
because it is part of the enclosing class's implementation. An inner class
can simply name the members of its enclosing object to use them. The
names in the enclosing class are all said to be
in scope.
The enclosing