wood burning stoves*
The moose likes Beginning Java and the fly likes local variable X is accessed from within inner class needs to be declared final Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "local variable X is accessed from within inner class needs to be declared final" Watch "local variable X is accessed from within inner class needs to be declared final" New topic
Author

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

sahar sa
Ranch Hand

Joined: Jul 06, 2009
Posts: 102
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

Joined: Oct 27, 2005
Posts: 19654
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
sahar sa
Ranch Hand

Joined: Jul 06, 2009
Posts: 102
sorry, change it! but what about my question?
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
sahar sa wrote:any suggestion?


Please provide a syntactically correct Java example demonstrating your issue.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38025
    
  22
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".
 
Don't get me started about those stupid light bulbs.
 
subject: local variable X is accessed from within inner class needs to be declared final
 
Similar Threads
final variable declared in a loop
private v.s public final
Inner class can not containt static varibales why?
A question about Inner Class
why inner class can't have static modifiers???