instance variable and initilization block : control flow
Vishwadeep Aggarwal
Greenhorn
Joined: Oct 30, 2012
Posts: 3
posted
0
Q: Here the question is that we are using the instance variable m before defining and initializing it but while compiling and executing this code it didn't show error. Also, if JVM first define and initialize the variable m then code must generates output as 3 2 1 but in actual the code generates the output as 2 3 1
The sequence of events when initializing class instances are described in the JLS here. The key points that affect this sample code:
Instance variables are initialized to their default values
A constructor is chosen and its parameters are evaluated
The object's super-class instance is intialized
The instance's instance initializers are executed and instance variables assigned in the order the initializers and variables are encountered in code
The constructor's body is executed.
So what happens is:
1) The variable m is initialized to null first
2) The instance initializer is executed first because it appears in code first
3) The instance variable m is evaluated and assigned next
4) The constructor is executed
Steve
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32712
4
posted
0
It shows why it can be poor practice to mix initialisers and constructors. Unless, as you are doubtless doing here, using the following universal justification:-
I just wanted to see what happens if …
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: instance variable and initilization block : control flow