Anonymous Classes

An anonymous class is a class definition that does not include a class name.  Since the class does not have a name it can only be instantiated when it is define.

Anonymous classes often implement an interface.  When they do we can store the reference to the anonymous class in a variable having the interface type.

In the example below we define an interface named Foo that includes one method named bar.  Rather than creating an inner class that implements Foo, we declare a variable f of type Foo and initialize it to a class object whose definition is provided on the right hand side of the assignment statement.  In that definition we provide an implementation for the bar method.  After we initialize f we can call bar on f.

public class Driver {
    interface Foo {
        public void bar();
    }

    public static void main(String ... args) {
        Foo f = new Foo() {
            public void bar() {
                System.out.println("Hello");
            }
        };

        f.bar();
    }
}

Iterable Example

In the example below, the Pair class implements Iterable<T>.  As such it must return back an instance of a class that implements Iterator<T>.  Rather than declaring an inner class, we can return an instance of an anonymous class.

import java.util.NoSuchElementException;
import java.util.Iterator;

public class Point<T> implements Iterable<T> {
    private T x;
    private T y;

    public Point(T x, T y) {
        this.x = x;
        this.y = y;
    }

    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private int count = 0;
            public boolean hasNext() {
                return count < 2;
            }
            public T next() throws NoSuchElementException {
                if (count >= 2) throw new NoSuchElementException();
                    return (count++ == 0) ? x : y;
                }
            };
    }
}

Button Handlers

Anonymous classes are often used when defining event handlers for GUI elements.  An event handler is a method that is called when an event is triggered.  For example when we create a button in a GUI we need to specify what happens when the button is pressed.  The button press is the event and method that is invoked when the event occurs is called a handler.

In JavaFX, some event handlers are implemented using objects that implement the EventHandler<ActionEvent> interface.  This interface requires a single method named handle that has a single ActionEvent parameter.  Rather than defining a class that implements this interface and then having to create an instance of the class to pass to a method that registers the handler, we can use anonymous classes and create and pass an instance of the class to the registering method in one statement.

The example below shows how to register a handler using an inner class. We first must create an inner class then pass an instance of the class to setOnAction.

private class ButtonHandler implements EventHandler<ActionEvent> {
    public void handle(ActionEvent event) {
         label.setText("AfterPress");
    }
}
...
button.setOnAction(new ButtonHandler());

The next example shows how we can create an instance of the EventHandler interface when we call setOnAction.

button.setOnAction(new EventHandler<ActionEvent>() {
    public void handle(ActionEvent event) {
        label.setText("AfterPress");
    }
});

© 2017 – 2019, Eric. All rights reserved.