I'm familiar that all local variables will be stored inside stack memory and objects and static variables will be stored in heap. But then when I came across the following code which confuses me.
public class Outer {
private int a =10;
public void outerMethod() {
int x = 30;
class Inner {
private int b = 20;
public void innerMethod() {
System.out.println("The Value of a is: "+a);
System.out.println("The Value of b is: "+b);
System.out.println("The Value of x is: "+x);
}
};
Inner inner = new Inner();
inner.innerMethod();
}
}
The above code runs fine. But my question here is x is a local variable of outerMethod(). And when we create an object of Outer class, and invoke outerMethod() on it, x will be stored inside a stack frame, and I'm also defining a class definition of Inner class and creating object of it, then I'm invoking innerMethod() on it.
So that Inner Class's object must be stored inside heap. If that's the case then how could it access x??