I came across these questions recently, and could not find the answer on StackOverflow;
- In what order are Java class variables initialised?
- And the somewhat related question, could re-ordering the variables change class behaviour?
- Why?
As suggested on Meta I will be posting my answer to this question.
In Java, class variables are initialised in the following order:
1 & 2 are only done the very first time that a class is instantiated.
So, given the following code:
Then we get the following output:
From this output we can see that the fields are initialised in the order specified in the list.
Now, as to the second question, can re-ordering the fields change the class behaviour. Yes, by re-ordering the fields you change the initialisation order of the fields. Now, in the specific case where all of the fields are independent, this won't affect the observed behaviour, however whenever the fields are not independent, for example in the above code, then re-ordering the fields could change their initialised values.
For example, if the three lines:
are changed to:
Then the output would change to:
That is,
ss2
, andss1
would change values.The reason for this is that this behaviour is specified in the Java Language Specification.