aspose file tools*
The moose likes Beginning Java and the fly likes about method-inner classes 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-inner classes" Watch "about method-inner classes" New topic
Author

about method-inner classes

Santhi Bharath
Ranch Hand

Joined: Jun 03, 2008
Posts: 75
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


thanks and regards<br />Santhi Bharath<br />SCJP 5.0, SCWCD 5.0
Shahnawaz Shakil
Ranch Hand

Joined: Aug 04, 2008
Posts: 57
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

Joined: Jun 03, 2008
Posts: 75
very thank you for your reply. OK ,then where are the FINAL variables stored?.is it heap?.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19761
    
  20

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 ]

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3018
    
  10
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: about method-inner classes