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

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

    Variable definitions are not done "before" blocks. They are both done at the same time, in the order that they are defined

    class SomethingWrongWithMe {
        {
            b = debug("block 1");
        }
        int b = debug("define");
        {
            b = debug("block 2");
        }
        private int debug(String str) {
            System.out.println(str);
            return 0;
        }
    }
    

    Output

    block 1
    define
    block 2
    

提交回复
热议问题