As opposed to an instance constructor, a static constructor of a class cannot be called explicitly in the source code. Instead, it is called automatically by the runtime sometime between the start of the program and the instantiation of the first object of the class. The static constructor is declared by writing the static keyword in front of the name of the class and by ending the line with empty parentheses (see Syntax Box 13.3). The statements are positioned in a block after this header.
There are a couple of notable differences between the declaration of a static constructor and an instance constructor. First, because the static constructor can only be accessed by the runtime, it makes no sense to specify an access modifier. Second, because the runtime wouldn't know which arguments to provide, no formal parameters can be specified.
The static constructor is not only typically used to initialize static variables (see the example in Syntax Box 13.3), but also used to perform other tasks that must be done once before the first instance of a class is created.
Syntax Box 13.3 The static Constructorstatic <Constructor_identifier> ( ) { <Statements> } Notes:
Example: class Fish { private static int numberOfFishCreated; static Fish() { numberOfFishCreated = 0; } ... } |
Tip
The call to the static constructor of a class could take place right after the start of the program, just before the creation of the first instance of the class, or somewhere in between. It all depends on the runtime's frame of mind. Because of this timing uncertainty, you should not let the static constructor contain any statements that are sensitive to timing. |