File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How initializer blocks help to share a block of code between multiple constructors? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How initializer blocks help to share a block of code between multiple constructors?" Watch "How initializer blocks help to share a block of code between multiple constructors?" New topic
Author

How initializer blocks help to share a block of code between multiple constructors?

Varuna Seneviratna
Ranch Hand

Joined: Jan 15, 2007
Posts: 167
http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html

In this page Under Initializing Instance Members there is:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.


What is meant by the above?
[ December 15, 2008: Message edited by: Varuna Seneviratna ]

Varuna Seneviratna
BV Boose
Ranch Hand

Joined: Jul 26, 2008
Posts: 33
It means that the code between the curly braces will be called by every constructor of the class.

produces:
I am an intializer block, somebody called me
I'm constructor number 1
I am an intializer block, somebody called me
I'm constructor number 2
I am an intializer block, somebody called me
I'm constructor number 3
3 different constructors all called
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2709
    
    5

Varuna, please consider making your subject line more descriptive. I can hardly make out anything of it. Read this to know why this is important. You can edit your post by clicking the .


SCJP, SCWCD.
|Asking Good Questions|
Amit Ghorpade
Bartender

Joined: Jun 06, 2007
Posts: 2709
    
    5

.. and while we are on the topic, you might also want to take a look at the order in which initialization blocks and constructors are invoked.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How initializer blocks help to share a block of code between multiple constructors?
 
Similar Threads
Initialization block.
Initializing Instance Members
java code format help
K&B Ch3 Self Test Que 14: need more clarification
Duplicate variables and initialization blocks