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

后端 未结 8 1992
萌比男神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条回答
  •  猫巷女王i
    2020-11-22 00:35

    You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.

    You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..

    A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.

提交回复
热议问题