Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

About Method local inner class

 
MohamedSalim malik
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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

 
Walter Ho
Greenhorn
Posts: 22
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can modify your commented line to be init block.
 
MohamedSalim malik
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 22
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot Walter.. sorry for this delay to reply. your solution did work .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic