How does Java – class object relationships work?

What happens when we create an instance of a class? I mean, every field and method of the class will be inside the object (with allocated memory), or it has nothing inside and has a reference to its class (the first option looks like a waste of memory.)

Solution

Whenever a new object is created, new memory is allocated in heap space (dynamic memory) This space is reserved for all content specific to a single instance of this class This means that each field (instance field, not static field) has its own independent location in memory For methods, things are different because they are common to all instances of a class, which means that there will be a method in memory and each instance of a class will reference them If you want to know where the local variables of a stored method are: they are stored on the stack, which means that they are not shared between calls to the method In addition, the method is stored in the "code memory" separate from the instance field

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>