• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Varuna Seneviratna
Ranch Hand
Posts: 170
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
BV Boose
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 .
 
Amit Ghorpade
Bartender
Posts: 2854
10
Fedora Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
.. 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic