We all know, that according to JLS7 p.4.12.5 every instance variable is initialized with default value. E.g. (1):
public class Test {
private Integer a;
No, they're not equivalent. Default values are assigned immediately, on object instantiation. The assignment in field initializers happens when the superclass constructor has been called... which means you can see a difference in some cases. Sample code:
class Superclass {
public Superclass() {
someMethod();
}
void someMethod() {}
}
class Subclass extends Superclass {
private int explicit = 0;
private int implicit;
public Subclass() {
System.out.println("explicit: " + explicit);
System.out.println("implicit: " + implicit);
}
@Override void someMethod() {
explicit = 5;
implicit = 5;
}
}
public class Test {
public static void main(String[] args) {
new Subclass();
}
}
Output:
explicit: 0
implicit: 5
Here you can see that the explicit field initialization "reset" the value of explicit
back to 0 after the Superclass
constructor finished but before the subclass constructor body executed. The value of implicit
still has the value assigned within the polymorphic call to someMethod
from the Superclass
constructor.