Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • 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: 2856
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: 2856
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.
 
What are you doing? You are supposed to be reading this tiny ad!
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!