aspose file tools*
The moose likes Beginning Java and the fly likes What can method local inner class object do? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "What can method local inner class object do?" Watch "What can method local inner class object do?" New topic
Author

What can method local inner class object do?

Vishram Khare
Greenhorn

Joined: Sep 23, 2007
Posts: 11
Hello everybody,

Suppose I define a method local inner class inside a method doStuff as--

public void doStuff(){
int local;

class MyInner{
System.out.println(local); //will not compile
}
}

This code will not compile because it is trying to access the local variable defined inside the method.The reason is that there could be objects of MyInner class created inside the doStuff() method and those local variables will go out of stack once the method doStuff() finishes execution.So the objects of MyInner class trying to access the local variables of the method does not make sense.

However why can the objects of MyInner class access the local variables inside doStuff() method if the local variables are declared final?Anyways final local variable would simply mean that its value cannot be changed.However it will go out of stack once the method finishes execution.In that case,how is it different from a non-final local variable?Anyways final local variable cannot be accessed from outside the method it is declared.So how can an instance of method local inner class (MyInner) access the final local variable?

Could anybody please let me know the same?

Thanks
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Final means it won't ever change so it's safe to make a copy in the object instance of the inner class. Then we don't care if the original goes out of scope.

I'd never seen a class defined inside a method. I had to put the println() inside another method to make it work:


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: What can method local inner class object do?
 
Similar Threads
Method-local inner class & final variables
Method local inner classes
Code for Method-Local Inner Classes not compiling
Method-local inner class and final local variable
Method Local Inner Class Pg 671 Kathy Sierra and Bates SCJP 6