import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
public class Test {
public static void main(String[] args) throws IOException {
new Test().go();
}
public void go() {
int period = 2000;
int delay = 2000;
double lastPrice = 0;
double price = 0;
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
lastPrice = price;
}
}, delay, period);
}
}
若如此使用,myeclipse会提示“Cannot refer to a non-final variable price inside an inner class defined in a different method”,可见多半不同方法的局部变量非final的不行,类的成员变量是可以的,经试验,的确如此~但为什么只能访问final型局部变量呢,仅仅是因为有可能造成在局部变量死亡后还有可能去引用局部变量吗?
参考: