Page 693 - Introduction to Programming with Java: A Problem Solving Approach
P. 693

                If a class is limited in its scope such that it is needed by only one other class, you should define the class as an inner class (a class inside of another class). Since a listener is usually limited to listening to just one class, listeners are usually implemented as inner classes.
It’s not required by the compiler, but inner classes should normally be private. Why? Because the main point of using an inner class is to further the goal of encapsulation and using private means the outside world won’t be able to access the inner class. Note the private modifier in the above Listener class heading.
Besides furthering the goal of encapsulation, there’s another reason to use an inner class as opposed to a top-level class (top-level class is the formal term for a regular class—a class not defined inside of another class). An inner class can directly access its enclosing class’s instance variables. Since listeners normally need to access their enclosing class’s instance variables, this is an important benefit.
16.11 Anonymous Inner Classes
Take a look at the GreetingAnonymous program in Figures 16.6a and 16.6b. It’s virtually identical to the previous Greeting program. Can you identify the difference between the GreetingAnonymous program and the Greeting program?
16.11 Anonymous Inner Classes 659
  /***********************************************************
*
GreetingAnonymous.java
Dean & Dean
        Apago PDF Enhancer
This program demonstrates an anonymous inner class.
***********************************************************/
*
*
*
import javax.swing.*;
// for JFrame, JLabel, JTextField
// for FlowLayout
import java.awt.event.*; // for ActionListener, ActionEvent
import java.awt.*;
public class GreetingAnonymous extends JFrame
{
private static final int WIDTH = 325;
private static final int HEIGHT = 100;
private JTextField nameBox; // holds user's name
private JLabel greeting;
// personalized greeting
//********************************************************
public GreetingAnonymous()
{
}
setTitle("Greeting Anonymous");
setSize(WIDTH, HEIGHT);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
createContents();
setVisible(true);
// end constructor
Figure 16.6a GreetingAnonymous program that has an anonymous inner class—part A



























































   691   692   693   694   695