This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

instance init block concept  RSS feed

 
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
Sheriff
Posts: 24217
38
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
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!