java - Cannot refer to a non-final variable inside an inner class defined in a different method -


edited: need change values of several variables run several times thorugh timer. need keep updating values every iteration through timer. cannot set values final prevent me updating values getting error describe in initial question below:

i had written below:

i getting error "cannot refer non-final variable inside inner class defined in different method".

this happening double called price , price called priceobject. know why problem. not understand why need have final declaration. if can see trying do, have around problem.

public static void main(string args[]) {      int period = 2000;     int delay = 2000;      double lastprice = 0;     price priceobject = new price();     double price = 0;      timer timer = new timer();      timer.scheduleatfixedrate(new timertask() {         public void run() {             price = priceobject.getnextprice(lastprice);             system.out.println();             lastprice = price;         }     }, delay, period); } 

java doesn't support true closures, though using anonymous class using here (new timertask() { ... }) looks kind of closure.

edit - see comments below - following not correct explanation, keeperofthesoul points out.

this why doesn't work:

the variables lastprice , price local variables in main() method. object create anonymous class might last until after main() method returns.

when main() method returns, local variables (such lastprice , price) cleaned stack, won't exist anymore after main() returns.

but anonymous class object references these variables. things go horribly wrong if anonymous class object tries access variables after have been cleaned up.

by making lastprice , price final, not variables anymore, constants. compiler can replace use of lastprice , price in anonymous class values of constants (at compile time, of course), , won't have problem accessing non-existent variables anymore.

other programming languages support closures treating variables specially - making sure don't destroyed when method ends, closure can still access variables.

@ankur: this:

public static void main(string args[]) {     int period = 2000;     int delay = 2000;      timer timer = new timer();      timer.scheduleatfixedrate(new timertask() {         // variables member variables instead of local variables in main()         private double lastprice = 0;         private price priceobject = new price();         private double price = 0;          public void run() {             price = priceobject.getnextprice(lastprice);             system.out.println();             lastprice = price;         }     }, delay, period);       } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -