Does the internal object in Java have a link?

If you have something like the following:

class MyClass { private class InnerClass { } } 

In java. Does the internal overhead class contain 4 bytes of reference, or is it contiguous with the parent class in memory? To clarify, in addition, it has 4 bytes of general service information about the object?

The "normal" java class has 8 bytes of overhead, 4 bytes and 4 bytes of other object information, does the inner class also have 8 bytes of this?

+4
source share
3 answers

Inner classes are similar to regular classes that are allocated to the heap when they are created, and any memory allocation for this will happen at this time. The inner class must know its parent class.

UPDATE . Based on your comment below - so technically inner classes are similar to regular classes, as I mentioned above, so that you could use memory when creating / using. Also, if you have static members in your inner class, this will add some memory usage since there will be a class object for the inner class.

Does this answer your question?

+2
source

Just decompile InnerClass using javap

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

In your example

 class MyClass { private class InnerClass { } } 

creating an MyClass object does not automatically create an InnerClass object, so the object cannot be "always inside an external object." Moreover, you can create any number of InnerClass objects for each MyClass object, so there can not be enough space for the MyClass object 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 

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

Thus, InnerClass objects have the same overhead as objects of ordinary classes and even additionally one link (for non-static inner classes), since each internal object must know its own external object.

+1
source

Source: https://habr.com/ru/post/1342443/


All Articles