Java:使用继承对外部 类 的引用数

Java: Number of References to Outer Classes using Inheritance

每个非静态嵌套 class 都保留对其外部 class 的引用,以便访问外部 class 的方法和字段。

鉴于此 class...

class Parent
{
    // some fields
    // some methods
    protected class NestedParent
    {
        // some other fields
        // some other methods
    }
}

...还有这个 class:

class Child extends Parent
{
    // some fields
    // some methods
    protected class NestedChild extends NestedParent
    {
        // some other fields
        // some other methods
    }
}

class NestedParent 引用了其外部 class Parent;因为 NestedChild 继承自 NestedParent 它也将具有该引用。但是,NestedChild 是否也会有对 Child 的单独引用,还是会使用继承的引用并将其强制转换为 Child 以访问 Child 的成员?

我问这个问题是因为我想弄清楚 NestedChild 的最终大小。如果它有一个额外的 4 字节引用,这对我正在工作的项目来说是一种很大的内存浪费,因为将有数百万个 NestedChild 实例。

您的理解没有错,因为每个 Child class 实例都是 Parent class 类型,因此 Child class 实例是 NestedChild[= 的外部封闭 class 10=]

NestedChild class 将仅引用 Child 实例,因此没有内存问题 here.Java 通过引用而不是通过实际对象工作,不像 C(没有指针的概念,只有references)。Child 实例持有对 Parent Class 成员的引用(参见对象图)。 对象引用是对象堆的一部分,class 定义位于方法区。

为清晰起见进行了编辑:-

尝试从 Child 中注释掉 "extends Parent",您会看到编译器抱怨 NestedChild inner class. 不存在类型为 Parent 的封闭对象