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

前端 未结 3 2662
無奈伤痛
無奈伤痛 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:32

    First of all, your assumptions are more or less correct, except for the fact that declarations (with initialization, such as int b = 0) and instance initializer blocks are executed in the order they are written.

    int b = 0;   // executed first
    
    {
        b = 1;   // executed second
    }
    
    int a = b;   // executed third
    

    Also note that the declaration i.e. int b is not executed. The declaration just declares the existence of the variable.

    As for the error you got (or, rather the error you didn't get) I agree that it looks strange. I assume that the compiler deals with referencing a variable in an expression and assigning a value to it in different ways. When writing to a variable in an instance initializer, it just checks that the variable is there, while when reading from it, it requires it to be declared above the instance initializer block. I'll see if I can find a reference for that in the JLS.

提交回复
热议问题