public class Main{
Main(){
int count = 3;
int test = 15;
Timer timer = new Timer();
TimerTask task = new TimerTask() {
@Override
public void run() {
if(count>0) {
System.out.println(count);
count--; // Local variable count defined in an enclosing scope must be final or effectively final
System.out.println(test);// 不會出錯
}else {
timer.cancel();
}
}
};
timer.schedule(task, 0,1000);
}
public static void main(String[] args){
new Main();
}
}
class Counter {
private int value;
public Counter(int i) {
value = i;
}
public int getValue() {
return value;
}
public void setValue(int i) {
value = i;
}
}
galaxian85
非常感謝您,想請問那為什麼把int count = 3;拿到Main()建構子外就不會出錯了呢,它也符合在匿名內部類別的"外部"呀?
你原本的 count 是 Main() 這個建構子的區域變數, 往外面放 count 就變成 class Main 的成員變數了, 不好意思是我沒有講清楚, "must be final or effectively final" 這個規則只適用於區域變數
了解了 謝謝您
Timer timer = new Timer() {
@Override
public void schedule(TimerTask task, long delay) {
super.schedule(task, delay);
System.out.println("schedule be performed");
}
};