Anonymous Classes

What Are Anonymous Classes

Anonymous classes are Java classes without names and used as an expression. The declaration and definition is done together. Anonymous classes are common in event driven programming. They are mainly used to implement interfaces with fewer methods.

Using Anonymous Classes

In our chat program, we use the Emitter.Listener from the Java Socket.IO client library interface for handling socket events. There is one method in the interface. Here is the interface definition of Emitter.Listener :

public class Emitter {    
    public interface Listener {
        void call(Object... var1);
    }
}

We can implement the interface with a normal class as follows :

class Connected implements Emitter.Listener {
    @Override
    public void call(Object... objects) {
        System.out.println("Connected to the server");
    }
}

Or we can implement the same interface using an anonymous class as follows :

//anonymous class definition and declaration
Emitter.Listener onConnected = new Emitter.Listener() {
    @Override
    public void call(Object... objects) {
        System.out.println("Connected to the server");
    }
};

Notice the anonymous class definition ends with a semicolon, (;), since its an expression. So you can interpret the above as, onConnected is a reference variable of type Emitter.Listener of a class without a name that implements the Emitter.Listener interface. Quite a mouthful.

Alternatively if we didnt need to use the anonymous object anywhere else, we could pass it directly into a method.

Socket socket = IO.socket("http://chat.peruzal.co.za");
// we are using the anonymous class as 
// a method parameter to the socket.on method
socket.on("connect", new Emitter.Listener() {
    @Override
    public void call(Object... objects) {
        System.out.println("Connected to the server");
    }
});

Summary

It is common to use anonymous classes when implementing interfaces with one or a fewer methods than creating a class to implement the interface.

Important things to note about anonymous classes

  1. Anonymous classes have access to local variables of its enclosing class.
  2. Anonymous classes can not modify local variables on its enclosing scope that are not declared final.

results matching ""

    No results matching ""