匿名内部类转换为lambda表达式

今天练习匿名内部类的写法,遇到这么个问题:

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硬是告诉我这里可以替换为lambda表达式,我百思不得其解,这种匿名内部类形式还能用lambda表达式替换?

但IDEA强大的智能提示功能一般是不会有错的,于是我开始在网上寻找替换的方法,最后变成了这样:

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();
    }
}

 运行,正确。哇,这样的写法真的是比写一个臃肿的匿名内部类或者内部类要简洁太多。

前面的event便是listener代码头的参数,箭头后面的内容便是代码块,由于这里只有一个语句,所以不需要有大括号。

如果有多条语句,就会是这样:

也是要比直接写内部类要简洁的多。

猜你喜欢

转载自www.cnblogs.com/MYoda/p/11246002.html