class Outer {
int o = 10;
class Inner {
int i = 20;
}
}
public class Demo {
public static void main(String args[]) {
Outer o = new Outer();
Outer.Inner oi = o.new Inner();
}
}
when we creating an inner class object through a outer class object how they both associate with each other in the heap ?
Basically the compiler implicitly creates a constructor taking a reference to the outer class, which is stored in a hidden field. So your code is somewhat like this:
class Outer {
int o = 10;
static class Inner {
private final Outer outer;
int i = 20;
Inner(Outer outer) {
this.outer = outer;
}
}
}
public class Demo {
public static void main(String args[]) {
Outer o = new Outer();
Outer.Inner oi = new Outer.Inner(o);
}
}
(Note that I've converted the inner class into a static nested class.)
See more on this question at Stackoverflow