Reputation: 7554
When you instantiate a new object by calling constructor, i.e.
Foo bar = new Foo(var);
When does the code in the constructor actually gets invoked in relations to object creation heap? When the constructors modifies member variables of bar, is storage for the variables already allocated and contain default values?
Upvotes: 0
Views: 1225
Reputation: 33141
Once new
is called it knows how much memory needs to be allocated into the heap for a variable of type, in your case Foo. Once that memory is allocated only then are the values set. Think about it how else are you going to assign member variables if you don't have memory for the member variable? If there is no memory new will throw an exception which you need to handle.
Process:
new
null
Upvotes: 3
Reputation: 20842
The constructor cannot be called until the memory exists.
For member variables, it is a recursive application of the same rule.
Upvotes: 0
Reputation: 27199
Here Foo bar = new Foo(var); we are creating bar object.When we use new keyword memory is allocated on the heap.The amount of memory allocated depends on the instance variables of the class.The JVM will calculate the amount of memory to be allocated, then using new it will allocate the memory.Here bar is a reference variable pointing on the heap where the object is allocated.
Upvotes: 0
Reputation: 26418
When JVM comes across new keyword it allocates the required memory for that class type, with if there is no initialization, then it initializes all the members to their default values, and if the member is an object then to null.
Upvotes: 0