This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Is init block copied to every constructor? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Is init block copied to every constructor?" Watch "Is init block copied to every constructor?" New topic
Author

Is init block copied to every constructor?

Martin Suska
Greenhorn

Joined: May 18, 2012
Posts: 1
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
internet detective
Marshal

Joined: May 26, 2003
Posts: 30050
    
149

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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37874
    
  22
Welcome to the Ranch

You might see it better if you print that class: try javap -c InitBlockTest for the bytecode.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is init block copied to every constructor?
 
Similar Threads
Instance blocks.
final modifier semantic broken?
enums do not allow access to static members within constructors and instance init blocks
code called before constructor
Question regarding Init block