What is the difference between a Class and an Object in terms of memory allocation?
Last updated
A class is a blueprint that mostly lives as code/metadata, while an object is a concrete instance that occupies real memory at runtime: defining a class allocates almost nothing per instance, but creating an object allocates space for its fields.
A class is a template:
Its definition (method code, type metadata) is loaded once into a shared area (e.g. the method area / metaspace in the JVM), not copied per object.
Methods are stored once and shared by all instances; only their code exists, regardless of how many objects you make.
An object is a runtime instance:
Each object gets its own memory block holding its instance fields, so N objects means N copies of the state.
Typically allocated on the heap; the variable you hold is usually a reference/pointer to that block (stack holds the reference in many languages).
Static vs instance:
static/class members live with the class (one copy); instance members live with each object.Lifetime: Class metadata lives as long as it is loaded; an object lives until it is no longer reachable and gets garbage-collected (or freed).