Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance init block concept

 
rakhee gupta
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If in a code we have a instance initialization code then that code is executed after the constructor's call to the super() is complete
so in the following program output should be:

class Init {
Init(int x) { System.out.println("1-arg const"); }
Init() { System.out.println("no-arg const"); }
static { System.out.println("1st static init"); }
{ System.out.println("1st instance init"); }
{ System.out.println("2nd instance init"); }
static { System.out.println("2nd static init"); }
public static void main(String [] args) {
new Init();
new Init(7);
}
}

1st static init
2nd static init
no-arg const
1st instance init
2nd instance init
1-arg const
1st instance init
2nd instance init

but the actual output is:
1st static init
2nd static init
1st instance init
2nd instance init
no-arg const
1st instance init
2nd instance init
1-arg const

please clear my understanding.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, your understanding is fine: the instance initializers are called right after the call to super(). The invisible call to super() happens as the very first thing in the constructor, before any of the statements you actually write in the body of the constructor. So for the constructor Init(), the compiler actually generates code as if you had typed this:
 
rakhee gupta
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you .now it is clear
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic