|
Free-floating blocks are defined within a class body, but not inside any method. They can appear anywhere in the class body and hence called floating. They are executed in the order of their appearance in the class.
Free-floating blocks are often used to initialization operations hence they are also-known-as initializers. An instance initializer is a free-floating block with no modifier. It is executed whenever an instance of a class is being created. Static Initializer is an free-floating block with static modifier. Being static, it is associated with the class and executed only once at the time of class loading. Thus you can be sure about the time of execution free-floating blocks, hence you can effectively use them to do the initialization job. Listing 3.19 illustrates a Product class with two free-floating blocks.

The first block with static keyword is a static initializer and is executed only once when the Product class is loaded. The second code block is an instance initializer and is executed whenever an instance of Product class is created. If we execute the InitializerTest class, the static initializer will be executed once (assuming that the Product class is not already loaded) and the instance initializer will be executed twice. Therefore, “Class initialized” is printed once, but “Instance initialized” is printed twice.