In Java, each object is allocated memory on the heap.The HotSpot JVM uses a data structure called Ordinary Object Pointers (OOPS) to represent pointers to objects.
All pointers (both objects and arrays) in the JVM are based on a special data structure called oopDesc.
Each oopDesc describes the pointer with the following information:
Mark word:
The mark word describes the object header. The HotSpot JVM uses this word to store identity hashcode, biased locking pattern, locking information, and GC metadata.
Klass word:
the klass word encapsulates the language-level class information such as class name, its modifiers, superclass info, and so on.
The layout of memory for an object
Object Header: The first few bytes of memory in an object are used to store its header information. This includes a reference to the object's class, a marker for garbage collection, and other metadata.
the object header consists of mark and klass words plus possible alignment paddings.
Instance Variables: The instance variables of an object are stored in the memory following the object header. These variables are the fields defined in the class, and they are allocated memory based on their type (e.g. int, double, object reference).
Padding: Java requires that each object be aligned to a multiple of 8 bytes. If necessary, padding bytes are added after the instance variables to ensure this alignment.
Object Footer: Some JVMs add an optional footer to the object to help with debugging and profiling. This footer typically contains a checksum or other metadata.
Java对象的访问定位
In Java, when you create an object using the new keyword, the JVM dynamically allocates memory to store the object.
When you create an object in Java, a reference variable is created to refer to the object. This reference variable holds a reference to the memory location where the object is stored. You can use this reference variable to interact with the object and access its methods and fields.