Java 中的内部 class 对象

Objects of an inner class in Java

Java 中的内部 class 的对象有一个特殊的 句柄 到外部对象,即 this[=12=]。但是,外部对象对内部对象的访问权限不同。

这允许内部对象访问外部变量或方法,即使它们是私有的。

这些假设是否正确?

来自JLS

When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used.

这意味着,是的,内部 类.

可以访问封闭 类 的实例变量

private 将访问限制在编译单元(源文件)的范围内,因此同一文件中的所有classes 都可以访问彼此的私有成员,无论它们是否是内部 classes。

关于内部 class 的唯一特殊之处在于(如您所说)它的每个实例都引用外部 class 的特定实例,但如果它以某种方式获得对另一个外部 class 实例(例如作为方法调用的参数),它也可以访问另一个实例的成员。类似地,如果外部 class 的实例以某种方式给出了对内部 class 实例的引用,它可以访问其成员,即使它没有 "own" 那个特定的内部class实例。