0

When I create a new Object the JVM allocates a memory block on the heap, regardless of the data that might come along. It might contain variables, it might contain methods. Let us call this mainObject. My question is that if there is another object ; lets call it childObject defined inside this Class of mainObject will the JVM assign a new memory block at a different memory location and setup some internal pointer from mainObject to childObject or will it define the memory location of childObject inside mainObject only.

Details of main class

     Public class mainClass{
public mainCLass(childClass childclass)
    }

Now this main class's object is created

mainClass mainclass = new mainCLass(childclass2);

Now the question is when the mainclass is being created a memory allocation is happening on heap. This object also has childClass childclass being passed in the constructor. Now my question is where is this childclass object getting created. In the same memory location as mainclass or someother memory location. Kindly let me know if there is still some doubt.

Tx

4
  • Objects can't have objects inside them. Commented Sep 20, 2014 at 1:44
  • Please clarify your vocabulary between "class" and "object", I can hardly understand what you want to say. Commented Sep 20, 2014 at 1:44
  • @Dici where did anyone mention classes? Commented Sep 20, 2014 at 1:47
  • 1
    What the JVM really does is allocate a single very large block of memory, and then it makes new objects in that one single block (which are almost certainly smaller than the very large block). But the JVM never allocates one object "inside" another as immibis said. At most you have a reference to an object inside another object, not the object itself. Commented Sep 20, 2014 at 1:59

1 Answer 1

2

In Java, variables of class types are always references. If a class contains a variable whose type is another class (as opposed to a primitive type like int), the object data in memory will contain just a pointer. Objects are never embedded within other objects. (Primitive types, however, are.)

(A reference doesn't actually have to be stored as a pointer, technically — it could be something like an integer index into a table of pointers kept elsewhere, to simplify the garbage collector's job of finding all the objects. The specifics are up to the JVM implementation. But regardless, it's something "pointer-like" that refers to an object located elsewhere on the heap.)

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

1 Comment

I get it. That is all I wanted to know .tx for that supersonic reply

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.