How inner class object resides in memory?

谁都会走 提交于 2019-12-29 04:24:26

问题


Outer outer = new Outer();

an Object of Outer class is created on heap and reference variable points to it.

If I understand it right when I write

Outer.Inner inner=outer.new Inner();

an object of Inner class is created on heap and inner points to it. In heap we have two separate objects which contains their own instance variables.

But if I write

Outer.Inner inner=new Outer().new Inner();

still two Object would be created on heap one for Outer and other for Inner. But with reference the inner only Inner Object's members are accessible . Who is referring to the outer Object on heap? If it is not referred by any reference then it should be eligible for garbage collection which would then impact the usage of inner.


回答1:


An inner class contains a hidden reference to its outer class instance. That hidden reference keeps the outer class instance alive if there are no other references to it.

To see this in action, take this source code and compile it:

public class Outer {
    public class Inner {
    }
}

Now use the java class inspection tool javap to see the hidden reference:

$ javap -p Outer\$Inner
Compiled from "Outer.java"
public class Outer$Inner {
  final Outer this$0;
  public Outer$Inner(Outer);
}

You'll see that there is a package-scope hidden reference called this$0 of type Outer - this is the reference that I talked about above.




回答2:


Each instance of an inner class holds a reference to an instance of its outer class. It's the reference that you get when you write Outer.this within one of the inner class's methods. The anonymous Outer instance won't be eligible for garbage collection unless all Inner instances associated with it are also eligible for garbage collection.




回答3:


Naturally, the inner holds on to strong references of the things it wants strong references to - like the other half of its instance variables which reside in Outer.



来源:https://stackoverflow.com/questions/30905491/how-inner-class-object-resides-in-memory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!