The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Method Local Inner classes Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Method Local Inner classes" Watch "Method Local Inner classes" New topic
Author

Method Local Inner classes

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 261
The inner class object cannot use the local variables of the method the inner class is in.

Because the local variables aren't guaranteed to be alive as long as the method-local inner class object, the inner class object can't use them. Unless the lcoal variables are marked final.



This message was edited 1 time. Last update was at by jose chiramal

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 261
One more question to add to this :

Page 672 K&B :

"You can't for example mark method-local inner class public,private, protected, static, transient and the like. -- Why so ?

For the purpose of the exam, the only modifiers you can apply to a method-local inner class are abstract and final".
Ankit Garg
Saloon Keeper

Joined: Aug 03, 2008
Posts: 9023

1. Since the variable is final in the method, so the local class gets a copy of the variable. When an instance of the local class is created, it gets a copy of the final variables of the enclosing method. There is no problem with this as we know that the value of final variables cannot be changed, so the copy of the final variable that the local class has is always same as the value of the final variable in the method.
2. What is the use of marking any declaration inside a method private or protected or static?? The declarations in a method are available only inside the method, so marking them public or private is useless...


Javaranch SCJP FAQ | SCWCD Links
vishnu viswanath
Greenhorn

Joined: Nov 03, 2011
Posts: 2
I tried to run your code with the outer variable 'x' as final and didn't get any error.?


got this output:
Outer x is :Outer2
local variable z is:local variable

You cannot access a variable inside method unless its final, since in that case each method invocation will have to keep its own instance of local variable.

Correct me if I am wrong.
 
 
subject: Method Local Inner classes
 
MyEclipse, The Clear Choice