内部类必须引用封闭类吗? [英] Must Inner classes have a reference to the enclosed class?

查看:125
本文介绍了内部类必须引用封闭类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内部类(非静态),该类在初始化时使用对封闭类的引用.内部类现在会保留对封闭类的引用吗?

I have an inner class (non-static) which is using a reference to an enclosing class in its initialization. Will the inner class keep a reference to the enclosing class now?

class Enclosing {
  class Inner {
    private final ABC innerField = outerField.computeSomething();
  }

  private final XYZ outerField = something();
}

更新

我非常清楚,可以Enclosing.this引用外部类.

I am very much aware that one can reference the outer class with Enclosing.this.

但是,如果该类不使用引用,那么在编译后该引用必须存在吗?即使仅在初始化中使用引用也有必要吗?

But, if the class doesn't use the reference, must the reference be there after compilation? Is it necessary even if the reference is only used in the initialization?

它在哪里说内部类总是 持有对外部类的引用?

Where does it say that an inner class always holds a reference to the outer class?

推荐答案

一个非静态嵌套类始终包含对封闭类的引用.在您的示例中,您可以将Inner中的封闭类引用为Enclosing.this.

A non-static nested class always holds a reference to the enclosing class. In your example, you can reference the enclosing class from Inner as Enclosing.this.

JLS 8.1.3 内部类和封闭实例" :

类O的直接内部类C的实例i与O的实例相关联,该实例称为i的直接封闭实例.对象的直接封闭实例(如果有)是在该对象确定时确定的被创建(第15.9.2节)."

"An instance i of a direct inner class C of a class O is associated with an instance of O, known as the immediately enclosing instance of i. The immediately enclosing instance of an object, if any, is determined when the object is created (§15.9.2)."

这篇关于内部类必须引用封闭类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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