Method Local Inner Class ! REWORKED!

Today I got a comment on my blog entry HERE.

When I went through my blog again, I was surprised to see that the thing I explained there was not right, probably at that time my understanding was not good enough. So I apologize for providing the wrong information. I will explain it again here :
Considering the same example :

class MyClass{
public void showValue(){
final int x = 0;
class MyInnerClass{
public void showOuterVar(){
System.out.println(“Hi I am method local Inner Class” + x);
}
}
}
}
Now as I explained earlier, the local variables of the method live on the stack, and exist only for the lifetime of the method. As we know that the scope of a local variable is limited to the method the variable is declared in so, When the method ends, the stack frame is blown away and the variable is history. But even after the method completes, the inner class object created within it might still be alive on the heap if, for example, a reference to it was passed into some other code and then stored in an some variable. Because the local variables are not guaranteed to be alive as long as the method-local inner class object, the inner class object can’t use them.
So we mark the local variables as final. When marked final now our class can use it.

Here is the correct reason :
As a part of optimizing the java code, what JAVA Programmers at SUN did, they made the JVM do some WORK, So in this case when this class is compiled there will be two class files (MyClass.class & MyClass$MyInnerClass.class) and the the value of the final variable is stuffed in the inner class i:e: we will have a variable “val$x” in the inner class. Compiler does this because it knows that the variable is final so there is no harm in inserting the value as it is, in the class. You probably won’t be able to see this in your compiler class but it does this way only. The fact can be verified in another way. When you open you class file of the inner class you will see a variable “this$0”, this is actually a reference to the outer class, this is the reason that you can access the outer class variables without any reference. So this is it works. I had a lot of discussion among my friend before writing this and we decided on this only. 🙂
So if anyone gets to know a better reason, Please do share with us. Thanx. enjoy.

Advertisements