Nested Classes


So far we have declared top-level classes. It is also possible to declare a class inside another class. This is called a nested class. Nested classes can be defined inside any block of code including method definitions, they can be either static or instance (also known as an inner class), and they can be given public , protected , private , or default access.

Why would you define a nested class? One reason is to give a class direct access to the fields of another (outer) class without giving the outer class members public or protected access. Nested classes are commonly used in writing event handlers for GUI applications. There are three general types of nested classes ”static, instance (inner), and anonymous inner.

Static Nested Classes

A static nested class is designated using the static keyword in the class declaration statement. It is associated with its outer class directly rather than with an instance of its outer class. A static nested class can define and access static fields, but does not have direct access to the instance members of its outer class.

A static inner class is the only way you can define a static class. You can't define a stand-alone class as static. Static nested classes can be defined inside other static nested classes. A static nested class can be referred to outside of the outer class using the syntax

 OuterClass.InnerClass 

Instance Nested Classes

A nonstatic nested class is called an inner class. It is associated with an instance of its outer class and can only exist within an instance of its outer class. In other words, you can't create an instance of an inner class without first creating an instance of the outer class. The outer class can create and manipulate an instance of an inner class. The inner class has direct access to the members defined in the outer class. An inner class cannot define static fields unless they are static and final .

Example: Using an Inner Class as an Event Listener

One situation where you will typically use inner classes is in developing GUI applications. When a user interacts with a GUI component, objects called events are generated. The events are sent to an event listener object that defines methods that respond to the event. The event listener often needs access to the fields from the GUI application. If the event listener class is defined as an inner class of the GUI application class, the event listener has direct access to the GUI application fields. Event listeners and Java GUI development in general are covered in more detail in Chapter 26.

In this example, a button is used to clear the contents of a text field. The button will generate an ActionEvent object when it is pressed. The button registers an ActionListener that responds to the event by clearing the text field. Because the ActionListener needs access to the text field, the ActionListener class is implemented as an inner class of the EventDemo class.

When you run this example, you will see a frame appear on your screen with a label, text field, and button. Type something into the text field. Now click the Clear button and any text inside the text field will disappear.

 import javax.swing.*; import java.awt.event.*; public class EventDemo extends JFrame {   JTextField pressureTF;   JLabel pressureLabel;   JButton clearButton;   public EventDemo() {     //  A label and text field are created     pressureLabel = new JLabel("pressure");     pressureTF = new JTextField(10);     //  A button is created and registered with an event     //  listener.  The event listener is an instance of     //  an inner class.     clearButton = new JButton("clear");     clearButton.addActionListener(                        new ActionHandler());     //  The GUI components are added to the frame.     //  The frame is sized and made visible.     JPanel panel = new JPanel();     panel.add(pressureLabel);     panel.add(pressureTF);     panel.add(clearButton);     getContentPane().add(panel);     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     setBounds(100,100,300,150);     setVisible(true);   }   //  The ActionHandler class is an event listener for   //  ActionEvents.  Because it needs access to the   //  pressureTF component, the class is implemented   //  as an inner class.  When the "clear" button is   //  clicked, the text in the textfield is cleared.   class ActionHandler implements ActionListener {     public void actionPerformed(ActionEvent event) {       pressureTF.setText("");     }   }   public static void main(String args[]) {     EventDemo demo = new EventDemo();   } } 

Anonymous Inner Classes

An anonymous inner class is a special type of inner class that provides a compact inner class definition. An anonymous inner class has no name or modifiers. The class declaration is incorporated into the syntax used to create an instance of it. Only one, unnamed instance of the class can be created. Anonymous inner classes result in more compact programs but they do make a code listing more difficult to read. They are intended for single-use applications such as GUI component event handlers.

Example: Using an Anonymous Inner Class

The AnonDemo class is the same as the EventDemo class seen in the previous example except that the event listener is implemented as an anonymous inner class. The inner class declaration is incorporated into the syntax used to register the button with the event listener. The code listing is somewhat shorter and somewhat more difficult to follow.

 import javax.swing.*; import java.awt.event.*; public class AnonDemo extends JFrame {   JTextField pressureTF;   JLabel pressureLabel;   JButton clearButton;   public AnonDemo() {     //  A label and text field are created     pressureLabel = new JLabel("pressure");     pressureTF = new JTextField(10);     //  A button is created and registered with an event     //  listener.  The event listener is an instance of     //  an anonymous inner class so the class definition     //  is included in the syntax for creating an     //  instance of it.     clearButton = new JButton("clear");     clearButton.addActionListener(         new ActionListener() {           public void actionPerformed(ActionEvent ae) {             pressureTF.setText("");           }         });     //  The GUI components are added to the frame.     //  The frame is sized and made visible.     JPanel panel = new JPanel();     panel.add(pressureLabel);     panel.add(pressureTF);     panel.add(clearButton);     getContentPane().add(panel);     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     setBounds(100,100,300,150);     setVisible(true);   }   public static void main(String args[]) {     AnonDemo demo = new AnonDemo();   } } 

Output ”

The GUI display will be the same as in the "Using an Inner Class as an Event Listener" example.



Technical Java. Applications for Science and Engineering
Technical Java: Applications for Science and Engineering
ISBN: 0131018159
EAN: 2147483647
Year: 2003
Pages: 281
Authors: Grant Palmer

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net