What happens in the memory when a class instantiates the following object?
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; } }
In class SomeClass1:
SomeObject so1 = new SomeObject('some property value');
In class SomeClass2:
SomeObject so2 = new SomeObject('another property value');
How is memory allocated to the newly instantiated object and its properties?
Let’s step through it:
… is actually more complicated than it looks, because you’re creating a new String. It might be easier to think of as:
(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.)
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.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.Bear in mind that
strSomePropertyis just a reference to a String. For now, it’ll be initialised to null.Next, the constructor is executed.
All this does is copy the reference to the String, into your
strSomePropertyfield.Finally, space is allocated for the object reference
so1. This is set with a reference to the SomeObject.so2works in exactly the same way.