Inner Classes

There are times when you need a class as a helper for another class. You could create a new class, make all the data and methods private and use that. But this produces extra files and compile steps. You can create classes inside other classes. These are called nested or inner classes. The inner class has access to all the outer classes data and methods. This is true even if they are marked private. This makes sense because the inner class is as much a part of the outer class as any of the data elements.

These inner classes can be static, but then they can't reference the data elements of the outer class. If the inner class is not static, there is an instance of it for each instance of the outer class. Non-static inner classes can't have static methods. We will see this quite often as they are a convenient way to create event handlers for GUI elements.

Anonymous Inner Classes

We have seen how we can define classes inside other classes. We have used this to create event handlers and such. We can also create classes without giving them names. These are called Anonymous Inner Classes. An example of their use is in the creation of the WindowAdapter class we frequently use in example code to handle window closing. Here is and example.

import RunButton;
import java.awt.*;
import java.awt.event.*;
/**
 * This is the simple driver for the button program
 * it creates the button panel object and displays it.
 * 
 * @author Kent Archie
 * @version 1.0
 */
public class ButtonMain
{
    public static void main(String[] args)
    {
      RunButton joe = new RunButton();
      joe.addWindowListener(
			new WindowAdapter () {
   					public void windowClosing (WindowEvent event) { 
						System.out.println("Goodbye");
						System.exit(0);
	       			}
								}
			    );
      joe.show();  
    } // main
}
Note that as the argument to the addWindowListener method we call new. The argument to new is what looks like a constructor call for the WindowAdapter class. However, we actually have a class definition in there. Inside, we override the windowClosing() method. What happens is the system creates an unnamed class that extends WindowAdapter and uses the code in the braces to define it.

Doing this saves a few lines of code but its purpose is to completely hide the class we use to handle the window closing. Since there is no named class, there is no way to create other instances of it without duplicating the code. There are places where this can be handy and is presented as another thing to have in your toolbox when you need. Also, I want to help make your thinking about objects to be more abstract. The full code for this is here.