Anonymous inner class into a lambda expression

Today, practice writing anonymous inner classes, encountered such a problem:

public class exercise {
    public static void main(String[] args) {
        NumClock numClock = new NumClock(1000);
        numClock.start();

        JOptionPane.showMessageDialog(null,"Quit the program?");
        System.exit(0);
    }
}

class NumClock {
    int sep;
    int n = 0;
    public NumClock(int sep){
        this.sep = sep;
    }

    public void start() {
        ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println(++n);
            }
        };
        Timer timer = new Timer(sep, listener);
        timer.start();
    }

}

IDEA he just told me lambda expressions can be replaced, I am puzzled that this form of anonymous inner classes can be replaced with a lambda expression?

But IDEA powerful intelligent prompts generally can not be wrong, so I began looking for ways to replace the Internet, and finally turned into this:

class NumClock {
    int sep;
    int n = 0;
    public NumClock(int sep){
        this.sep = sep;
    }

    public void start() {
        ActionListener listener = event -> System.out.println(n++);
        Timer timer = new Timer(sep, listener);
        timer.start();
    }
}

 Run correctly. Wow, this is really writing than writing a bloated anonymous inner class or inner classes to be too simple.

Event listener is in front of the parameter code is the head, behind the content block arrow is, since there is only one statement, there is no need braces.

If more than one statement, it will be like this:

Than is written directly to the internal classes and more concise.

Guess you like

Origin www.cnblogs.com/MYoda/p/11246002.html