2

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 Answer 1

3

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()));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.