This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

instance variable and initilization block : control flow

 
Vishwadeep Aggarwal
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
 
Steve Luke
Bartender
Pie
Posts: 4181
21
IntelliJ IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
     
    Campbell Ritchie
    Sheriff
    Pie
    Posts: 47244
    52
    • 0
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    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 …
     
    Don't get me started about those stupid light bulbs.
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic