Saturday 26 September 2015

Secret of anonymous inner class

Why the method local variable access within inner class needs to be final or effectively final?

How Inner class access the variable of its enclosing class :
  • instance variable :  All inner class contains an internal reference of its enclosing outer class. Using this reference it access the instance variable of the outer class.
  • static/class variable : It is quite straight forward; it uses the class name directly to access the static variables
  • method local variable : This is the place where the inner class does not have any reference to the local variable since the local variables are created inside stack memory area in JVM. So the outer and inner class have an agreement that any method local variable accessed inside inner class are not going to be modified in future by declaring as final.If the local variable is not declared as final but not modified once it is assigned with the initial value, then that variable is known as effectively final. This time the inner class have the individual copy of local variables those are accessed inside inner class and which will not allow to to modify those variables at any cost.
Example Source Code : 
Compiled Inner class Code : 

No comments:

Post a Comment