• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

question about method-local class

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1.class MyOuter2{
2. private String x = "Outer2";
3. void dostuff(){
4. String z = "local variable";
5. class MyInner{
6. public void seeOuter(){
7. System.out.println("Outer x is :" + x);
8. System.out.println("local variable zs :" + z);
9. }
}
}
}
The eighth line is erro :won't compile,but if i change the fourth line with "final String z = "local variable";" The eighth line can be right. Why? And what is the function of final here? thank you!
 
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Method local inner class should not be allowed to access method local variable because method local variables are stored in a stack, where as method local inner class object is stored in a heap. Scope of method local variables are limited to that method only. But your method can pass the reference of the method local inner class object to some other method which can keep the method local inner class object live even if method gets over.

So, if method local inner class object is used by any other method, then that object will explode if the access to method local variables are allowed, as those local variables are already out of scope.
 
Sheriff
Posts: 9708
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Gguo please Use Code Tags when you post a source code. You can edit your message using button and then add code tags to it...
 
reply
    Bookmark Topic Watch Topic
  • New Topic