Java 8 Lambda Expressions - what about multiple methods in nested class

Optimal Prime picture Optimal Prime · Feb 17, 2014 · Viewed 59k times · Source

I'm reading about the new features at: http://www.javaworld.com/article/2078836/java-se/love-and-hate-for-java-8.html

I saw the example below:

Using Anonymous Class:

button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
        System.out.println("Action Detected");
    }
});

With Lambda:

button.addActionListener(e -> {
    System.out.println("Action Detected");
});

What would someone do with a MouseListener if they wanted to implement multiple methods within the anonymous class, e.g.:

public void mousePressed(MouseEvent e) {
    saySomething("Mouse pressed; # of clicks: "
               + e.getClickCount(), e);
}

public void mouseReleased(MouseEvent e) {
    saySomething("Mouse released; # of clicks: "
               + e.getClickCount(), e);
}

... and so on?

Answer

Reimeus picture Reimeus · Feb 17, 2014

From JLS 9.8

A functional interface is an interface that has just one abstract method, and thus represents a single function contract.

Lambdas require these functional interfaces so are restricted to their single method. Anonymous interfaces still need to be used for implementing multi-method interfaces.

addMouseListener(new MouseAdapter() {

    @Override
    public void mouseReleased(MouseEvent e) {
       ...
    }

    @Override
    public void mousePressed(MouseEvent e) {
      ...
    }
});