What is the difference between a static and a non-static initialization code block

后端 未结 8 1838
萌比男神i
萌比男神i 2020-11-21 23:32

My question is about one particular usage of static keyword. It is possible to use static keyword to cover a code block within a class which does not belong to

8条回答
  •  孤街浪徒
    2020-11-22 00:33

    The code block with the static modifier signifies a class initializer; without the static modifier the code block is an instance initializer.

    Class initializers are executed in the order they are defined (top down, just like simple variable initializers) when the class is loaded (actually, when it's resolved, but that's a technicality).

    Instance initializers are executed in the order defined when the class is instantiated, immediately before the constructor code is executed, immediately after the invocation of the super constructor.

    If you remove static from int a, it becomes an instance variable, which you are not able to access from the static initializer block. This will fail to compile with the error "non-static variable a cannot be referenced from a static context".

    If you also remove static from the initializer block, it then becomes an instance initializer and so int a is initialized at construction.

提交回复
热议问题