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

后端 未结 8 1807
萌比男神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:35

    "final" guarantees that a variable must be initialized before end of object initializer code. Likewise "static final" guarantees that a variable will be initialized by the end of class initialization code. Omitting the "static" from your initialization code turns it into object initialization code; thus your variable no longer satisfies its guarantees.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题