在看《java核心技术 卷一》的时候,发现如下问题:
匿名内部类传递参数需不需要final关键词修饰的问题!
package com.test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.JOptionPane;
import javax.swing.Timer;
public class AnonymousInnerClass {
public static void main(String[] args) {
TalkingClock tc = new TalkingClock();
tc.start(1000, true);
JOptionPane.showConfirmDialog(null, "OK?");
System.exit(0);
}
}
class TalkingClock{
public void start(int interval, final boolean beep){
ActionListener listener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
Date now = new Date();
System.out.println("At the tone, the time is " + now );
if(beep){
System.out.println("bibibibibibibibbi~~~~~~~~~~~~~");
}
}
};
Timer t = new Timer(interval,listener);
t.start();
}
}
内部类TalkingClock的方法start(int interval, final boolean beep),因为是在匿名内部类(new ActionListener()后的代码)中使用,所以要用final关键字修饰,但是我发现: 如果我用jdk1.8编译就不需要使用final关键字去修饰变量!估计是1.8有所改动吧,只知道增加了lambda表达式,原来此处也有修改么?