How to replace the listeners with anonymous classes in Java?

Viewed 45

I have an interface called ClientRegistrationListener

public interface ClientRegistrationListener {
     void onClientAdded(Client client);
}

And I also have in the main class an ArrayList of ClientRegistrationListener. In this list I add listeners for my class.

listeners.add(new PrintClientListener());

where PrintClientListener is a class created in this main class

class PrintClientListener implements ClientRegistrationListener, Serializable {
    private static final long serialVersionUID = 2777987742204604236L;

    @Override
    public void onClientAdded(Client client) {
        System.out.println("Client added: " + client.getName());
    }
}

My question is how can I replace the listeners from the Bank class with anonymous classes?

1 Answers

You can anonymously implement the interface by opening a block after the new call:

listeners.add(new ClientRegistrationListener() {
   @Override
   public void onClientAdded(Client client) {
       System.out.println("Client added: " + client.getName());
   }
});

Or, even more elegantly, since ClientRegistrationListener is a functional interface (even though it's not annotated as one), you can anonymously implement it with a lambda expression:

listeners.add(client -> System.out.println("Client added: " + client.getName()));
Related