开发者

Does an Internal Object in Java have a Reference?

If you had something like the following:

class MyClass {

    private class InnerClass {

    } 
}

In java. Does the inner class of the overhead of a 4 byte reference, or is it contiguous in memory with the parent class? To clarify, in addition does it have the 4 bytes of general object overhead information?

A "normal" java class has 8 bytes of overhead, a 4 byte 开发者_StackOverflow中文版reference plus 4 bytes of other information about the object, does an inner class also have 8 bytes of this?


Inner classes are like regular classes that get allocated on the heap when you create them and any memory allocation for that will happen at that time. An inner class will need to know its parent class.

UPDATE Based on your comment below - so technically inner classes are like normal classes as I mentioned above so you would incur memory usage when you create it/use it. Also if you have static members in your inner class it will add some memory usage since there will be a class object for the inner class.

Does this answer your question?


Just decompile InnerClass using javap

class MyClass$InnerClass extends java.lang.Object{
    final MyClass this$0;
    MyClass$InnerClass(MyClass);
}


In your example

class MyClass {
    private class InnerClass {
    } 
}

creating a MyClass object does not automatically creates an InnerClass object, so the object can't be "always inside the outer object". Even more, you can create any number of InnerClass objects for each MyClass object, so the MyClass object can't have enough space for all these objects.

//                                      numbers: MyClass  InnerClass
MyClass m = new MyClass();                 //        1         0
MyClass.InnerClass i = m.new InnerClass(); //        1         1
MyClass.InnerClass[] array =
   new MyClass.InnerClass[20];             //        1         1
for(int i = 0; i < 20; i++) {
   array[i] = m.new InnerClass();
}                                          //        1        21

A MyClass object can be used wherever any other object can be used, so they need all the normal information necessary for normal objects, too.

So, objects of the InnerClass have the same overhead as objects of normal classes, and even additionally one reference more (for non-static inner classes), since each inner object needs to know its outer object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜