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

查看:139
本文介绍了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");

...实际上比看起来更复杂,因为你正在创建一个新的String。可能更容易想到:

... 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实现的内部,所以只需要相信一块内存被用来表示某些属性值。此外,您有一些临时分配的内存,其中包含对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 只是对String的引用。现在,它将被初始化为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;

所有这一切都是将引用复制到String,进入你的 strSomeProperty field。

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天全站免登陆