When we create an object, do creation of object and the execution of constructor happens at the same time or first object is created then constructor execution take place?
Its written in the Herbert Schildt: "Once defined ,the constructor is automatically called immediately after the object is created ,before the new operator completes". My queue is that if new operator has not finished with it's memory allocation then how can be constructor be called before new gets completed as it's written constructor is called only after object is created.
Section 12.5 of the JLS gives the details. The bare bones of it is:
null
or 0)java.lang.Object
The JLS goes into more detail, of course, including cases where there isn't enough memory or a constructor body throws an exception.
The timing of each bit of the constructor is important though:
It's important to understand that if a superconstructor invokes an overridden method which reveals the value of a field, it will not have gone through the field initializer yet. So you can see the default value of the field rather than the value you'd expect to from the initializer. For example:
class Bar extends Foo {
private String name = "fred";
@Override public String toString() {
return name;
}
}
If the Foo
constructor calls toString()
, that will null
rather than "fred"
.
(If name
is final
, then it's treated as a constant in toString()
and other things happen, but that's a different matter.)
See more on this question at Stackoverflow