Java 对象的内存分配过程中的步骤 [英] Steps in the memory allocation process for Java objects

查看:30
本文介绍了Java 对象的内存分配过程中的步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个类实例化以下对象时,内存中会发生什么?

public class SomeObject{

    private String strSomeProperty;

    public SomeObject(String strSomeProperty){
        this.strSomeProperty = strSomeProperty;
    }
    public void setSomeProperty(String strSomeProperty){
        this.strSomeProperty = strSomeProperty;
    }
    public String getSomeProperty(){
        return this.strSomeProperty;
    }
}

在班级SomeClass1中:

SomeObject so1 = new SomeObject("some property value");

在班级SomeClass2中:

SomeObject so2 = new SomeObject("another property value");

如何为新实例化的对象及其属性分配内存?

推荐答案

让我们一步一步来:

SomeObject so1 = new SomeObject("some property value");

... 实际上比看起来更复杂,因为您正在创建一个新字符串.可能更容易想到:

... is actually more complicated than it looks, because you're creating a new String. It might be easier to think of as:

String tmp = new String("some property value");
SomeObject so1 = new SomeObject(tmp);
// Not that you would normally write it in this way.

(要绝对准确 - 这些并不是真正等效的.在原始版本中,新字符串"是在编译时创建的,并且是 .class 映像的一部分.您可以将其视为性能黑客.)

(To be absolutely accurate - these are not really equivalent. In the original the 'new String' is created at compile time and is part of the .class image. You can think of this as a performance hack.)

因此,JVM 首先为 String 分配空间.您通常不知道或不关心 String 实现的内部结构,因此只需相信一块内存用于表示某些属性值".此外,您临时分配了一些内存,其中包含对字符串的引用.在第二种形式中,它显式地称为 tmp;在您的原始形式中,Java 会在不命名的情况下处理它.

So, first the JVM allocates space for the String. You typically don't know or care about the internals of the String implementation, so just take it on trust that a chunk of memory is being used to represent "some property value". Also, you have some memory temporarily allocated containing a reference to the String. In the second form, it's explicitly called tmp; in your original form Java handles it without naming it.

接下来,JVM 为新的 SomeObject 分配空间.这是 Java 内部簿记的一点空间,也是对象的每个字段的空间.在这种情况下,只有一个字段,strSomeProperty.

Next the JVM allocates space for a new SomeObject. That's a bit of space for Java's internal bookkeeping, and space for each of the object's fields. In this case, there's just one field, strSomeProperty.

请记住,strSomeProperty 只是对字符串的引用.现在,它将被初始化为 null.

Bear in mind that strSomeProperty is just a reference to a String. For now, it'll be initialised to null.

接下来,构造函数被执行.

Next, the constructor is executed.

this.strSomeProperty = strSomeProperty;

所做的只是将引用复制到字符串中,复制到您的strSomeProperty字段中.

All this does is copy the reference to the String, into your strSomeProperty field.

最后,为对象引用so1分配空间.这是通过引用 SomeObject 设置的.

Finally, space is allocated for the object reference so1. This is set with a reference to the SomeObject.

so2 以完全相同的方式工作.

so2 works in exactly the same way.

这篇关于Java 对象的内存分配过程中的步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆