简体   繁体   中英

Java: Number of References to Outer Classes using Inheritance

Every non-static nested class keeps a reference to its outer class for the purpose of accessing the outer class's methods and fields.

Given this class...

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

... and this class:

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

The class NestedParent has a reference to its outer class Parent; because NestedChild inherits from NestedParent it will have that reference, too. However, will NestedChild also have a separate reference to Child or will it use the inherited reference and cast it to Child for accessing Child's members?

I ask this question because I am trying to figure out the final size of NestedChild. If it has one additional reference of 4 bytes this is a big waste of memory in the project I am working in since there will be millions of instances of NestedChild.

Your understanding is little wrong as every Child class instance is of type Parent class and so Child class instance is the outer enclosing class for NestedChild

The NestedChild class will have a reference to Child instance only,so no issue of memory here.Java works by reference and not by actual Object unlike C(there is no concept of pointers,only references).The Child instance holds reference to Parent Class members(see the Object graph). Object references are part of the Object heap and class definition lies in method area.

EDITED FOR CLARITY:-

Try commenting out "extends Parent" from Child,you would see that compiler complains that no enclosing object of type Parent is present for NestedChild inner class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM