Class Outer{int a;Outer (){a=10;}public static void main(String args[]){final Outer o1=new Outer();Outer o2=new Outer();class inner{inner(){o1.a=20;//allowed//o2.a=30; not allowed}}}}Why inner classes can access only final variables as illustrated? Thanks in advance!

Questions by sunil_dalvi82   answers by sunil_dalvi82

Showing Answers 1 - 2 of 2 Answers

omaha_inky

  • Jun 1st, 2006
 

From www.javaranch.com:

The inner class can't use local variables from the method in which the inner class is defined!
After all, at the end of that method, the local variables will be blown away. Poof. Gone. History. That inner object you created from that inner class might still be alive and kickin' out on the heap long after that local variable has gone out of scope.
You can, however, use local variables that are declared final, because the compiler takes care of that for you in advance. But that's it -- no method parameters from that method, and no local variables.

  Was this answer useful?  Yes

Kumar

  • Aug 21st, 2006
 

Inner classes can also access method parameters that are declared to be final.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions