aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Initialization sequence Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Initialization sequence" Watch "Initialization sequence" New topic
Author

Initialization sequence

Sven Thor
Ranch Hand

Joined: Jan 31, 2004
Posts: 34
According to "Core Java" by Sun, the initialization process when a constructor is called is:
1. All data fields are initialized to default value
2. All field initializers and initialization blocks are executed
3. Chained constructors (if any) are executed
4. The body of the constructor is executed
I am a bit confused as to where the implicit default constructor that is provided if no constructor is specified fits in to this sequence.
class T{
T(){
System.out.println("super()");
}
}
public class Test extends T{
{
System.out.println("block");
}
public static void main(String[] arg){
Test t = new Test();
}
}
This code prints "super" before "block". That seems to contradict the sequence above that initializer blocks are executed before constructors. Or does this sequence apply only to explicit constructors, while the implicit constructor is always executed before any blocks ?
ST
Vineela Devi
Ranch Hand

Joined: Dec 20, 2003
Posts: 191
Hi Sven,
The o/p given by your code doesnt contradict with the rules specified .
When u r trying to create a n instance of a subclass , the order will be as follows.
�Static variables r static blocks , if any r initialized (executed for blocks)in both superclass and subclass.
�Superclass variables r initialized.
�Default(no arg constr) of SuperClass is called.
�Variables of SubClass are initialized and intializers are executed depending upon the order defined
�Constructor of Subclass is called.
so, the code prints super () first and then block.
But, if u make a slight modification to ur code, rules willbe clear to u.

class T{

static{
System.out.println("static Block initialized");
}

T(){
System.out.println("super()");
}
}
public class Test extends T{
{
System.out.println("block");
}
static{
System.out.println("static Block Of Child initialized");
}
Test(){
System.out.println("Test()");
}
public static void main(String[] arg){
Test t = new Test();
}
}
so, in this case the o/p will be as follows:
static Block initialized
static Block Of Child initialized
super()
block
Test()
hope u got it.
vineela
Sven Thor
Ranch Hand

Joined: Jan 31, 2004
Posts: 34
Thanks a lot. Think I got it.
ST
 
 
subject: Initialization sequence
 
Similar Threads
class getting loaded
Object constructor and initialization
Regarding Block...
order when constructing
Initializing Instance Members