• Post Reply Bookmark Topic Watch Topic
  • New Topic

non-final variable inside an inner class defined in a different method - option - change to final

 
Charles Sexton
Ranch Hand
Posts: 273
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this code won't compile because selected row must be declared as final because of it being defined outside the window listener. Is their anyway around this? If I make it final the first time that the variable is called it keeps it starting value until the GUI is closed. This variable but be able to change, need advice on what to do or how you would do it.


 
Rob Spoor
Sheriff
Posts: 20822
68
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Charles Sexton wrote:this code won't compile because selected row must be declared as final because of it being defined outside the window listener. Is their anyway around this? If I make it final the first time that the variable is called it keeps it starting value until the GUI is closed. This variable but be able to change, need advice on what to do or how you would do it.

Make it final. The scope of the final variable is the actionPerformed method and the anonymous WindowAdapter. If you click the button once, the currently selected row is retrieved and put into local variable selectedRow. If you click on the button again, this is repeated. If another row is selected that means that selectedRow gets another value. Yes, the variable is final, but only within its scope.

As for the anonymous listener, the selectedRow is actually copied to a field of the anonymous listener. You can see this with the following (contrived) example:
If I decompile this with JAD I get the following:
You see that the x becomes field val$x which is set during object creation. Don't mind the syntax, it looks odd but that's what JAD makes of it. The main issue is that each time the anonymous class is instantiated, a new instance is created with its own copy of the final value - which changes for each click.
 
Charles Sexton
Ranch Hand
Posts: 273
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank You
 
Rob Spoor
Sheriff
Posts: 20822
68
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!