Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is init block copied to every constructor?

 
Martin Suska
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

recently I found that in Java tutorial is written

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.


In fact it seems, that it's not true. When I try

The output is


And while "in init" is printed jst once it seems to me that it's not copied in each constructor.

PS: tried with Java 6
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34378
346
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not copied into each constructor. It's called once per instantiation as you noted. In particular, it is called between calling the superclass's constructor and resuming your constructor. Since only one superclass constructor is called, there is only one place between that and your class.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

You might see it better if you print that class: try javap -c InitBlockTest for the bytecode.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic