堆中创建对象

本文深入探讨了Java对象在HotSpot虚拟机中的内存布局,包括对象头、实例数据和对齐填充三部分。详细解释了markword和类型指针的作用,以及基本类型和引用类型的存储方式,帮助理解Java内存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);//②

        }
    }

一、执行到①,栈、堆、方法区情况

在这里插入图片描述

二、执行到②,栈、堆、方法区情况

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值