In what order are initializer block and variable definitions and etc. executed? (in java)

前端 未结 3 2756
無奈伤痛
無奈伤痛 2021-02-20 18:51

I have problem understanding the order in which initialization happens. this is the order I assumed:

*Once per 
    1. Static variable declaration
    2. Static          


        
3条回答
  •  迷失自我
    2021-02-20 19:42

    The Java Language Specification (section 8.3.2.3) says you can use a variable on the left hand side of an expression, i.e. assign to it, before it is declared, but you cannot use it on the right hand side.

    All variables are initialized to their default values, then explicit initializers and anonymous blocks are run in the order they are found in the source file. Finally the constructor is called.

    Statics are only run once on the first use of a class.

    The compile error appears to be a rule of Java rather than something that necessarily makes sense in every case.

提交回复
热议问题