How is the internal object of a class in memory?
Outer outer = new Outer();
a Object
class Outer
is created on the heap and reference variables point to it.
If I get it right when I write
Outer.Inner inner=outer.new Inner();
class object Inner
is created on the heap and Inner
points to it. On the heap, we have two separate objects that contain their own instance variables.
But if I write
Outer.Inner inner=new Outer().new Inner();
two more Object
will be created in the heap, one for Outer
and the other for Inner
. But with reference, only members are Inner
available Inner
Object's
. Who is referencing the external Object
heap? If it doesn't link to any reference, it should be eligible for garbage collection, which will then affect usage Inner
.
The inner class contains a hidden reference to its own instance of the outer class. This hidden reference keeps the external instance of the class alive if there are no other references to it.
To see it in action, take this source code and compile it:
public class Outer {
public class Inner {
}
}
Now use the Java class validation tool javap
to see the hidden link:
$ javap -p Outer\$Inner
Compiled from "Outer.java"
public class Outer$Inner {
final Outer this$0;
public Outer$Inner(Outer);
}
You will see that there is a hidden link to the this$0
type application scope Outer
- this is the link I mentioned above.
Each instance of an inner class contains a reference to an instance of its outer class. This is the link you get when you write Outer.this
inside one of the methods of the inner class. An anonymous instance Outer
will not be eligible for garbage collection unless all of its associated instances are Inner
also eligible for garbage collection.
Naturally, the inner holds onto strong references to things it wants strong references to - as well as the other half of its instance variables, which are in the Outer.