内部类对象如何驻留在内存中? [英] How inner class object resides in memory?

查看:167
本文介绍了内部类对象如何驻留在内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Outer outer = new Outer();

Object of 在堆上创建了外部类,并且引用变量指向它。

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();

在堆上创建 Inner 类的对象, 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.

但如果我写

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

仍然是两个对象将在第一个堆上为外部创建,其他为内部。但是参考内部只有内部 对象的成员可以访问。谁在堆上引用外部对象?如果它没有被任何引用引用,那么它应该有资格进行垃圾收集,这会影响 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.

推荐答案

内部类包含对其外部类实例的隐藏引用。如果没有其它引用,那么隐藏引用会使外部类实例保持活动状态。

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 {
    }
}

现在使用java类检查工具 javap 查看隐藏的引用:

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);
}

你会看到有一个名为<$的包范围隐藏引用c $ c>这个$ 0 的类型 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.

这篇关于内部类对象如何驻留在内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆