How does class object relation work?

Berkay Tarhan :

What happens when we create an instance of a class? I mean, will every field and method of that class be inside that object (with allocated memory) or will it not have anything inside and have a reference to its class, instead. (First option looks like a waste of memory.)

Mike :

Whenever a new object is created, new memory is allocated in the heap space (dynamic memory). This space is reserved for everything that's specific to this single instance of a class. That means every field (instance field, not the static one) would have its own separate location in memory.

For methods, things are different since they are common for all instances of a class, which means you would have one method in memory which would be referred to by each instance of a class.
If you wonder where are local variables of a method stored: they are stored on the stack, meaning they are not shared between invocations of that method.

Also, methods are stored in the 'code memory', separate from instance fields.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=89339&siteId=1