• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Initialization sequence

 
Sven Thor
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 191
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot. Think I got it.
ST
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic