Java Reference
In-Depth Information
account .deposit(interest);
. . .
} // End of inner block
. . .
} // End of surrounding block
The same nesting works for inner classes. Except for some technical restrictions,
which we will examine later in this section, the methods of an inner class can access
the variables from the enclosing scope. This feature is very useful when
implementing event handlers. It allows the inner class to access variables without
having to pass them as constructor or method parameters.
Methods of an inner class can access local variables from surrounding blocks and
fields from surrounding classes.
Let's look at an example. Suppose we want to add interest to a bank account
whenever a button is clicked.
JButton button = new JButton("Add Interest");
final BankAccount account = new
BankAccount(INITIAL_BALANCE);
// This inner class is declared in the same method as the account and button
variables.
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
// The listener method accesses the account variable
// from the surrounding block
double interest = account .getBalance()
* INTEREST_RATE / 100;
account .deposit(interest);
}
};
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
There is a technical wrinkle. An inner class can access surrounding local variables
only if they are declared as final . That sounds like a restriction, but it is usually not
Search WWH ::




Custom Search