File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes About Method local inner class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "About Method local inner class" Watch "About Method local inner class" New topic
Author

About Method local inner class

MohamedSalim malik
Greenhorn

Joined: Feb 04, 2011
Posts: 19
Guys, I am Studying for OCJP exam. i got this problem today . Anyone please give me an answer for this



As you can see in this above code , i can print the variable 's' inside the method that is located inside the method local inner class. but why i cant print the same variable inside method local inner class itself(i commented out that line). it gives me a compilation error. anyone kind enough to explain me.
Walter Ho
Greenhorn

Joined: Apr 09, 2008
Posts: 22


Normally, why would you not define a class like this?

Walter Ho
Greenhorn

Joined: Apr 09, 2008
Posts: 22

You can modify your commented line to be init block.
MohamedSalim malik
Greenhorn

Joined: Feb 04, 2011
Posts: 19
My problem is , i can access( or print) that s variable from inside the method; but i cannot access( or print ) it from the class itself. when i try to do like that(uncommenting the line) it gives me a compilation error. why is that?
As i know, a method local inner class can access any instance variable from the outer class. but here i get a compilation error. thank you
Walter Ho
Greenhorn

Joined: Apr 09, 2008
Posts: 22

MohamedSalim malik wrote:My problem is , i can access( or print) that s variable from inside the method; but i cannot access( or print ) it from the class itself. when i try to do like that(uncommenting the line) it gives me a compilation error. why is that?
As i know, a method local inner class can access any instance variable from the outer class. but here i get a compilation error. thank you


I think you misunderstand my explanation with a question.
One would not define a class like Test, because the System.out.println(s) is not in a method.
If you enclosed it within {}, then the init block would work. s is definitely accessible.
MohamedSalim malik
Greenhorn

Joined: Feb 04, 2011
Posts: 19
Thanks alot Walter.. sorry for this delay to reply. your solution did work .
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About Method local inner class