Heap space in Java is used for dynamic memory allocation for Java objects and JRE classes at the runtime. New objects are always created in heap space and the references to this objects are stored in stack memory.
在HotSpot虚拟机中,对象在内存中存储的布局可以分为3块区域:对象头(Header)、 实例数据(Instance Data)和对齐填充(Padding)。
HotSpot虚拟机的对象头包括两部分信息,第一部分用于存储对象自身的运行时数据, 如哈希码(HashCode)、GC分代年龄、锁状态标志、线程持有的锁、偏向线程ID、偏向时 间戳等,统称为mark word,另一部分是类型指针,即对象指向它的类元数据的指针,虚拟机通过这个指 针来确定这个对象是哪个类的实例。
对齐填充,非必须。
An object’s member variables are stored on the heap along with the object itself. That is true both when the member variable is of a primitive type, and if it is a reference to an object.
实例数据:基本类型存放值;引用类型存放引用
Static class variables are also stored on the heap along with the class definition.
类变量存放在方法区中(java8后方法区在堆中)
public class Point {
private int x;
//省略getter、setter
public Point(int x) {
this.x = x;
}
}
public class Circle {
private Point p;
private int c;
//省略getter、setter
public Circle(Point p, int c) {
this.p=p;
this.c=c;
}
}
//测试方法
public class Test {
public static void main(String[] args) {
int x=12;
int c=20;
Point point=new Point(x);//①
Circle circle=new Circle(point,c);//②
}
}