1

Let's say we have an instance reference variable assigned to an object.

public class Player {
     private Object object = new Object();
}

whenever I create a new Player instance.

Player player = new Player();

As far as I have learned, might be wrong I'm pretty new to this. The heap allocates memory for the instance primitive variables and stores these in the objects.

If it does the same for the instance reference variable which is assigned to an object, doesn't this instantly create a new instance or does this only occur when calling the reference variable?

5
  • In java the objects are stored in heap and the pointer(address of the location) is assigned to a location in the stack. Commented Jul 7, 2017 at 12:55
  • Java allocates memory for an instance once it see the "new" key word, and the reference is updated with the container object. More information docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/geninfo/… Commented Jul 7, 2017 at 13:00
  • duplicate of stackoverflow.com/questions/8588152, stackoverflow.com/questions/6396440, stackoverflow.com/questions/19402207. In short, depends on the JVM and whether escape analysis allows allocation on the stack. Commented Jul 7, 2017 at 13:00
  • i'll have read on that @sanojmathew thanks! I'm not talking about local variables Njol, just unsure of whether the objects are created upon creating a new instance of the class(the assigned instance reference belongs to) Commented Jul 7, 2017 at 13:05
  • @JobinJohnson: No, that's an oversimplification. In particular, the object field (as it's part of an object) is on the heap, not on the stack. Commented Jul 7, 2017 at 13:24

1 Answer 1

0

If I'm understanding your question correctly, instantiating a new Player instance (on the heap) also instantiates a new Object (on the heap), and the Player instance holds a reference to the Object instance. Java doesn't do "lazy" instantiation.

Sign up to request clarification or add additional context in comments.

8 Comments

So basically, this would take up unnecessary memory and it would be better to just create an Object whenever it's required?
enclosed instances are always created. So, if you don't need the instance don't create it.
Java actually does a form of lazy instantiation.
@Dave, what makes the instantiation "unnecessary"?
@LewBloch Let's say I simply require this Object to be instantiated on certain circumstances, it would take up unnecessary memory to have it instantiate whenever a new Player is instantiated, right?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.