Prerequisites: Java Basics Part 3

Get a brief introduction to Callbacks, Events, Event Sources, and Event Listeners/Handlers in Java.


A callback is a piece of code that you can pass as an argument to some other code. The code can then execute this passed callback as its own. Since Java doesn’t yet support function pointers, they are implemented as Command objects. For example:

public class Test {
    public static void main(String[] args) throws  Exception {
        new Test().doWork(new Callback() { // implementing class            
            public void call() {
                System.out.println("callback called");

    public void doWork(Callback callback) {
        System.out.println("doing work");;

    public interface Callback {
        void call();

A callback method can be any method in any class. The callback acts as - a reference to an instance of the class maintained in another class. When some event happens in that other class, it calls the method from the first. The only thing that makes it a callback as opposed to any other method call is the idea of handing a reference to an object so that the object can invoke a method on the callback later. The callback usually holds a reference to a state and is triggered on some event.

In loading the callback implementation with all the dependencies of your code, we create separation between our code and the code that is executing the callback


A change in the state of an object is known as an event. In other words, an event describes the change in the state of the source. Events are generated as a result of user interaction with the graphical user interface (GUI) components. For example, an event is generated when a user clicks on a button, moves the mouse, enters a character through a keyboard, selects an item from a list, or scrolls the page Java defines many such Event Classes inside the java.awt.event package.

Some of these events are ActionEvent, MouseEvent, KeyEvent, FocusEvent, and ItemEvent.

Event Sources

A source is an object that generates an event. An event generation occurs when the internal state of that object changes in some way. A source must register listeners for the listeners to receive notifications about a specific type of event. Some of the event sources are Button, CheckBox, List, Choice, and Window.

Event Listeners/Handlers

A listener is an object that is notified when an event occurs. A listener has two major requirements; it should be registered to one more source object to receive event notifications from, and must implement methods to receive and process those notifications.

Java has a set of interfaces defined for receiving and processing the events under the java.awt.event package.

Some of the listeners are ActionListener, MouseListener, ItemListener, KeyListener, and WindowListener.

Check your knowledge!


Which of these classes is a superclass of all the events?









Question 1 of 20 attempted