Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

local variable X is accessed from within inner class needs to be declared final

 
sahar sa
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I search about this error there are many examples and disscutions on net but I still can not understand . If I'm righ, This error means that I have to declare mentioned variable as a final variable so that in the rest of program I will not be able to change it?
If yes, what shall I do, because I have this error and I need to change the variable after the inner class has been finished.
My code is something like:
Class A(X,Y){
new B(){
price = X;

}
if (X==Y)
price = Y--;

}

and it throws me arror in price variable at new B() inner class! I can not declare price as a final because may be later on I need to change it(in if ). what should I do?
any suggestion?

Thanks,
Sahar.
 
Rob Spoor
Sheriff
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sahar sa wrote:I can not declare price as a final cuz May later on I need to change it(in if ). what should I do?
any suggestion?

You should start by using real words.
 
sahar sa
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sorry, change it! but what about my question?
 
Embla Tingeling
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sahar sa wrote:any suggestion?


Please provide a syntactically correct Java example demonstrating your issue.
 
Campbell Ritchie
Sheriff
Pie
Posts: 48968
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The inner class may exist after the local variable has gone out of scope and been taken off the stack. So the inner class has to retain a copy of that local variable. What if the value changes during execution of the method? Then there might be two values to that variable. It would be very difficult for a compiler to follow the execution of that method, so it is very difficult to record the changes for the inner class. So the rules are: no changes allowed. This can only be implemented by making the local variable "final".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic