When I pass an anonymous inner class into a function, I can refer to variables in the current scope from within a method of that class, like so:
class Caller {
private Object callerPrivate;
// ...
public void someMethod() {
final String callerLocal = "Eyes only";
ISomeInterface anon = new ISomeInterface() {
public void doSomethingInterfacy {
System.out.println(callerPrivate.toString());
System.out.println(callerLocal);
}
};
// this is some other object that puts ISomeInterfaces in a queue
// and makes them doSomethingInterfacy later
myCallManager.enqueue(anon);
}
}
Now, after someMethod above has been run, the Caller and the queue with the little anons can go separate ways, and, as far as I understand it, the JVM keeps all the references straight so that this always works.
But what if, for example, the queue gets serialized, the program shut down and restarted, and after that the queue gets deserialized and the items in it shall be run, with the Caller instance long gone and forgotten?
And are there other ways for the surrounding object and the anonymous inner class to get separated in a way that calls inside the anon class won't work anymore?