class MyOuter {
private String x = "Outer";
void doStuff() {
int y=10;
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
System.out.println("Value of y:"+y); // this is not possible
}
}
MyInner mi = new MyInner();
mi.seeOuter();
}
public static void main(String a[])
{
MyOuter ob=new MyOuter ();
ob.doStuff();
}
}
Inner classes within the method can not access the variables inside
the method. I found a reason from some java book as below.
"The local variables of the method live on the stack, and exist only
for
the lifetime of the method. You already know that the scope of a local
variable is
limited to the method the variable is declared in. When the method
ends, the stack
frame is blown away and the variable is history. But even after the
method
completes, the inner class object created within it might still be
alive on the heap if,
for example, a reference to it was passed into some other code and
then stored in an
instance variable. Because the local variables aren't guaranteed to be
alive as long
as the method-local inner class object, the inner class object can't
use them. Unless
the local variables are marked final! The following code attempts to
access a local
variable from within a method-local inner class"
My question is the object of inner class is not accessible or it cant
be instantiated outside this method.
Look at the following code:
class MyOuter {
private String x = "Outer";
public MyInner doStuff() // here i m getting error that "u can not
return object ob inner class"
{
int y=10;
class MyInner {
public MyInner seeOuter()
{
return this;
}
}
MyInner mi = new MyInner();
MyInner innerOb=mi.seeOuter();
return innerOb;
}
public static void main(String a[])
{
MyOuter ob=new MyOuter ();
ob.doStuff();
}
}
Why this is not allowing me to throw inner class object(innerOb)
outside the method(doStuff()).
Then how the references of inner class can stay alive when the method
goes out of scope or it is done its execution?
It is really confusing me. Please somebody make me clear.
--
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/javaprogrammingwithpassion?hl=en