Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

access of non final variable from method local inner class

 
rohit shekhar
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


above code is generating error unless x is not final. In book what they explained I am not able to understand. Please explain.
 
Praveen Kumar M K
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If its not too much of an effort, do type out the gist of what was given in the book and what you didn't understand. It'll help the folks here to get to heart of the issue, right away.

Thanks,
Praveen.
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Local inner classes cannot access the local variables defined in the method in which the local classes are defined. the reason is when the local inner class in instantiated , the object as you know is created on the heap. the thing is that this object can have more lifetime than the local variables which defined in the method , which are created on the stack and which once method completes are blown off the stack . so you cannot access local variables from local inner classes. however if you make the variables final, then the local inner classes can access them. this is because , in this case, the object of the inner class gets reference to the local variable that has been declared as final . so even after the method completes the object can access the local variable. the point is that the actual variables has been lost but the reference is there with the inner class object and it seems as if we are accessing the original variable. you can disassemble the class file using javap and you can see the result.

 
Enkita mody
Ranch Hand
Posts: 333
Firefox Browser Java Windows XP
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ankita modi. wrote:http://javarevisited.blogspot.in/2011/12/final-variable-method-class-java.html


thats been few months back ankita. the person probably does not need the answer.
 
Enkita mody
Ranch Hand
Posts: 333
Firefox Browser Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
gurpeet singh wrote:
ankita modi. wrote:http://javarevisited.blogspot.in/2011/12/final-variable-method-class-java.html


thats been few months back ankita. the person probably does not need the answer.


Okey dokey nice
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic