File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Method local Inner Class question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Method local Inner Class question" Watch "Method local Inner Class question" New topic

Method local Inner Class question

aniruddha panadare

Joined: Dec 23, 2008
Posts: 15
Why Method Local inner class can Access local variables marked as "final"?
Sachin Adat
Ranch Hand

Joined: Sep 03, 2007
Posts: 213
Because the JLS says so..........

Now, why the JLS says so is because during the execution of your inner class implementation, it creates the objects on the heap.
Now if the inner class object has access to local variables of the method, the objects of the class may use them
even after the method has completed its execution, ie. when they don't reside on the stack.
But, if it is final, its value cannot be changed, so its OK to use the variable, since it will be constant.

How To Ask Questions On Java Ranch - How To Answer Questions On Java Ranch
Ankit Garg

Joined: Aug 03, 2008
Posts: 9453

Aniruddha a method local class has a copy of the final constants and parameters of the method. That's why it can access them. This is implemented internally by the compiler. You can read my blog to be more clear. The URL is in my signature

SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 45359
More difficult a question than we usually have here on beginners'.

I agree. Here's the link:
subject: Method local Inner Class question
It's not a secret anymore!