java - Ordering of instance variable initializers -
it seems intuitively clear in java, instance variable intitializers executed in order in appear in class declaration.
this appears case in jdk using. example, following:
public class clazz { int x = 42; int y = this.z; int z = this.x; void print() { system.out.printf("%d %d %d\n", x, y, z); } public static void main(string[] args) { new clazz().print(); } }
prints 42 0 42
(in other words, y
picks default value of z
).
is ordering guaranteed? i've been looking through jls, , can't find explicit confirmation.
yes, is.
the se7 jls covers instance variable initialization order in 12.5 execution section:
...
4. execute instance initializers , instance variable initializers class, assigning values of instance variable initializers corresponding instance variables, in left-to-right order in appear textually in source code class. if execution of of these initializers results in exception, no further initializers processed , procedure completes abruptly same exception. otherwise, continue step 5.
...
the jls java 5 mentions in "classes" section:
the static initializers , class variable initializers executed in textual order.
Comments
Post a Comment