I've recently started learning about Static Blocks and Instance Initializers. I wrote this program that tries the two concepts out.
As I understand it, static blocks are blocks of code between curly brackets in a class marked by the keyword "static". They are executed once and only once when the class is loaded (this apparently was not always true for previous versions, but is fixed in 1.4).
Instance Initializers are blocks of code between curly brackets (without the keyword "static"). They are executed every time the class is instantiated before the constructor is called. These can be used to initialize an anonymous class-- anonymous classes can't have a constructor, as they have no name.
One thing which is a bit odd is that it *looks* like the instance initializers are being called before the constructors, but this is not the case-- I read up on the order in which these events happen:
1. Memory for the object is allocated on the heap.
2. That memory is cleared, setting data fields to be set to zero, 0.0, null, etc.
3. The class constructor is called.
4. The parent classes constructors are called recursively.
5. Explicit initializers in the constructor are called, and any Instance Initializers are called.
6. The rest of the statements in the class constructor are called.
The code for printing messages from the constructors falls into step 6, so it finishes after the Instance Initializers are called.
Does this all seem correct? Do they usually ask about things like this on the certification exam?
Thanks in advance.
--
Zeno
(This post comes from related posts I originally started at
http://www.javajunkies.org)
[ April 10, 2003: Message edited by: Tim Allen ]
[ April 10, 2003: Message edited by: Tim Allen ]
Edited by Corey McGlone: Added Code Tags
[ April 10, 2003: Message edited by: Corey McGlone ]