Tom said:
Yes and no, the latter is a shortcut to the former. It DOES run the
constructor code before the inline declaration/creation objects
definitions though.
Careful. Variable initializers and instance initializers are run after
the *superclass'* constructor but before the (rest of) the constructor
body for the class in which they appear. This is as specified in JLS(2e)
8.8.6. It is easy to write a test class that demonstrates this behavior:
public class InitOrder {
int initWithInitializer = 42;
int initInConstructor;
public InitOrder() {
/*
* Implicit invocation of Object() occurs here
*
* The instance variable initializer then runs before the
* (rest of) the constructor body.
*/
System.out.println("At constructor start:");
System.out.println(" initWithInitializer = "
+ initWithInitializer);
System.out.println(" initInConstructor = "
+ initInConstructor);
/*
* The last println() above shows initInConstructor with its
* default value
*/
initInConstructor = 17;
System.out.println("At constructor end:");
System.out.println(" initWithInitializer = "
+ initWithInitializer);
System.out.println(" initInConstructor = "
+ initInConstructor);
}
public static void main(String[] args) {
InitOrder instance = new InitOrder();
System.out.println("After constructor:");
System.out.println(" initWithInitializer = "
+ instance.initWithInitializer);
System.out.println(" initInConstructor = "
+ instance.initInConstructor);
}
}
====
D:\temp\testdir>java -cp . InitOrder
At constructor start:
initWithInitializer = 42
initInConstructor = 0
At constructor end:
initWithInitializer = 42
initInConstructor = 17
After constructor:
initWithInitializer = 42
initInConstructor = 17
====
John Bollinger
(e-mail address removed)