When compiling the following code, i got compile error:
MadScientist.java:27: Error: local variable timeTraveler is accessed from within inner class; needs to be declared final
import java.util.*;
interface TimeTravelCallback {
void leaped(int amount);
}
interface TimeTraveler {
void adjust(int amount);
}
class LinearTimeTraveler implements TimeTraveler {
@Override public void adjust(int amount) {
}
}
public class MadScientist {
public static void main(String[] args) {
MadScientist madScientist = new MadScientist();
TimeTraveler linearTimeTraveler = new LinearTimeTraveler();
madScientist.experiment(linearTimeTraveler);
}
public void experiment(TimeTraveler timeTraveler) {
TimeTravelCallback cb = new TimeTravelCallback() {
@Override public void leaped(int amount) {
timeTraveler.adjust(amount); //error message
}
};
cb.leaped(20);
}
}
If I change
public void experiment(TimeTraveler timeTraveler) {
to
public void experiment(final TimeTraveler timeTraveler) {
then it works.
Is there any other fix without adding the 'final' at the method parameter?