File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about method-inner classes

 
Santhi Bharath
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why can't a method inner object use the local variables of that method unless
those are declared FINAL.can any body explain in detail.thanks in advance
 
Shahnawaz Shakil
Ranch Hand
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You will get the answer of your question if you think about the consequences of method local inner class using variables of the same method. Local variables of the method exists only for the lifetime of the method. When the method ends, the stack and the variable is also destroyed. But even after the method completes, the inner class object created within it might still be alive on the heap. And if this object tries to access a variable which is no more then!!!
 
Santhi Bharath
Ranch Hand
Posts: 75
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
very thank you for your reply. OK ,then where are the FINAL variables stored?.is it heap?.
 
Rob Spoor
Sheriff
Pie
Posts: 20369
44
Chrome Eclipse IDE Java Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Because the variable is final, the inner class instance keeps a copy of that variable's value - either primitive, or the reference to an object. If the variable was a reference to an object, this object will still have at least one reference (in the inner class) and not be garbage collected.

So yes, in the end, its value is stored on the heap, within the instance.
[ August 19, 2008: Message edited by: Rob Prime ]
 
Mike Simmons
Ranch Hand
Posts: 3028
10
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This isn't really a Beginner question, is it?

Since JDK 6, you can't always be sure that objects will be stored on the heap. Sometimes, if the JVM can determine that an object is only accessible from within a single thread, and it can determine when the last variable referencing that thread has gone out of scope, it can allocate the memory for the object on the stack rather than the heap. This means it can be garbage collected very efficiently. It also means the JVM can ignore synchronization requests if it's already determined that no other threads can touch the object. This is useful for a class like StringBuffer, whose methods are synchronized but in most cases this is completely unnecessary.

Anyway, the point here is that nowadays it's often hard to know for sure whether an object is really on the heap, or on the stack. And it generally makes very little difference, from the programmer's perspective.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic