Using Inner Classes for Listeners

JButton button = new JButton(". . .");
// This inner class is declared in the same method as the button variable
class
MyListener implements ActionListener
{
   . . .
};

ActionListener listener = new MyListener();
button.addActionListener(
listener);

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);

Click here to see the example.

Why would an inner class method want to access a variable from a surrounding scope?

   Answer: Direct access is simpler than the alternative – passing
   the variable as a parameter to a constructor or method.


If an inner class accesses a local variable from a surrounding scope, what special rule applies?

   Answer: The local variable must be declared as final.