Java Reference
In-Depth Information
an issue in practice. Keep in mind that an object variable is
final
when the variable
always refers to the same object. The state of the object can change, but the variable
can't refer to a different object. For example, in our program, we never intended to
have the
account
variable refer to multiple bank accounts, so there was no harm in
declaring it as
final
.
Local variables that are accessed by an inner-class method must be declared as
final
.
412
413
An inner class can also access fields of the surrounding class, again with a restriction.
The field must belong to the object that constructed the inner class object. If the inner
class object was created inside a static method, it can only access static surrounding
fields.
Here is the source code for the program.
ch09/button2/InvestmentViewer1.java
1
import
java.awt.event.ActionEvent;
2
import
java.awt.event.ActionListener;
3
import
javax.swing.JButton;
4
import
javax.swing.JFrame;
5
6 /**
7
This program demonstrates how an action listener can access
8
a variable from a surrounding block.
9 */
10
public class
InvestmentViewer1
11 {
12
public static void
main(String[] args)
13 {
14 JFrame frame =
new
JFrame();
15
16
//
The button to trigger the calculation
17 JButton button =
new
JButton(
"Add
Interest"
);
18 frame.add(button);
19
20
//
The application adds interest to this bank account