Hi Everyone...I'm a little bit unclear about the following topics as they relate together: 1)the order of execution of instance initialization code 2)final variable initialization and 3)forward referencing.
From an
article (which I found referenced in (
thread)):
"When objects are created, the JVM invokes a compiler-generated <init> (instance initialization) method. There is one <init> method for every constructor in a class. Assuming the constructor does not explicitly invoke another constructor in the same class, <init> methods include code from instance variable initializers (transformed into assignment statements) and instance initialization blocks in textual order followed by the code from the corresponding constructor."
Therefore, the order of execution of initialization code should be:
1. instance initializers and instance initializer blocks in the order the appear.
2. THEN the code from the constructor.
I also read in K&B ver 1.4 Certification Study Guide cpt 2 page 95 regarding the initialization of final variables ...
"Don't count on the default value for final variables, though, because a final variable - even if it's an instance variable - won't be given one. The rule is: if you declare a final instance variable, you're obligated to give it an explicit value, and you must do so by the time the constructor completes."
So...
1. final variables DO NOT have default values.
2. and they can be initialized as late as code in the constructor (i.e., according to the previous article, after instance initializers and instance intializer block code runs).
Given, you can trick the compiler into allowing a forward reference by using a method, I ran code that initialized an instance variable (y)in an initializer that called a method (a()) which returned a forward reference to a final instance variable (z) that is later initialized in the constructor and which should not have a default value since it's a final variable.
I thought I would get a compiler error because I'm accessing z before it's initialized and z doesn't have a default value. However, the code compiles and runs fine and the output is:
C:\work>
java FFTest
z = 100
y = 0
So...what did I assign to y? How did this work?
Thank you so very much in advance for your help...Catherine
[EDIT: Added code tags and formatted code]
[ November 01, 2006: Message edited by: Henry Wong ]