Select Page

In Java, it is possible to write a class definition inside of another class definition. The inside class is called an inner class.

A class with an inner class

The inner class is usually made private. When an inner class is private, it is accessible only to the code in the class that contains it. The inner class is a private member of the outer class. The inner class, like other methods of the outer class, is accessible to only methods of the outer class. The class is defined inside the outer class because it is needed right in the outer class.

Inner classes are commonly used to write event listener classes to handle events from GUI components.

Program to demonstrate private inner class as event listener

Output

JButton Event Handling

After clicking on the button, an action event is created and passed on to the actionPerformed method of the private inner class. This executes to change the color of the content pane of the JFrame to red.

JButton Event Handling2

Event Handlers must implement an interface

An event listener class must always implement an interface. An interface has abstract methods. The class that implements an interface must override all these abstract methods and provide implementation for the methods. When a class implements an interface it establishes a contract between the class and the interface. This contract forces the class to override all the abstract methods of the interface and provide implementation.  

import statement for event handlers

Event listener interfaces are located in the java.awt.event package. Because of that, to use an event listener, you must precede your code with the import statement:

Note that the above import statement is a wildcard import statement. It makes all interfaces available for your program. You may however import specific interfaces only. Example: import java.awt.ActionListener imports the ActionListener interface and makes it available for your program.

The “implements” keyword

 You use the implements keyword in a class header to indicate that the class implements an interface. This means, the class has established a contract between itself and the interface. That is, the class has agreed to override the methods of the interface.

In the code below, the ButtonListener class implements the ActionListener interface. This forces the ButtonListener class to have a method called actionPerformed. Note that this method was overwritten in the ActionListener interface. The class provides an implementation (body of code) for the actionPerformed method.

Similarly, the class CheckBoxListener implements the interface ItemListener and thus, overwrites its method, ItemStateChanged, and provides implementation for it.There is always a contract between the class and the interface it implements and the class must honor this contract by providing implementation for all the methods of the interface.