Default constructor is automatically called after an object is created.
But in Java when we allocate memory using new operator i.e. classname obj = new classna
"...then how default constructor actually do so as the class has not come into physical existence. "
The class is already in memory, the new operator allocates memory space to hold the instance variables and parents instance variables specific to the new instance. But the class had come into physical existence before.
If we consider an example like
classname obj = new classname();
classname obj
initialize the object and new classname();
allocates memory location for the object. If you have a constructor, then the constructor is called, otherwise default constructor is called.
But in Java when we allocate memory using new operator i.e. classname obj=new classname(); the constructor is automatically invoked before new allocates memory to the class member's.
That is incorrect. The constructor is invoked after memory has been allocated.
@Jon Skeet's answer explains clearly the sequence of events that occur during object creation.
You may be confused by the fact that the constructors may well cause further objects to be allocated; e.g. during the execution of the declaration initializers. But these objects don't occupy memory in the original object; i.e. the object we are constructing.
If you want a definitive specification of what happens when an object is created, read the Java Language Specification - in particular JLS 12.5.
Default constructor is automatically called after an object is created.
Yes (if the default (no-argument) constructor was called).
Can someone explain me the same using a clear example.
I'm not sure I understand your question to 100 % but no where in the Java Language Specification it says that the constructor should run it's code before the memory for the object has been allocated.
This is explained in great detail with an example in Section 12.5: Creation of new Class Instances in the Java Language Specification.
The process is basically:
this
/ super
calls to other constructors) each level evaluating any arguments to the level above, but that's alljava.lang.Object
constructor is executed first, then the direct subclass, etc. This is also when variable initializers are executed. (Prior to this, the variables have their default values of null etc.)new
The idea of a default constructor has no meaning at execution time. It's just a parameterless constructor which calls super()
as far as the JVM is concerned.
The business about the constructor chain is exactly the same as it would be if these were methods with a first line which just chains to the next constructor along; it's just a stack of calls.