jQuery in Action, 3rd edition
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
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

Is init block copied to every constructor?

Martin Suska

Joined: May 18, 2012
Posts: 1

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

Joined: May 26, 2003
Posts: 33117

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.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46367
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?
It's not a secret anymore!