Understanding instance and static blocks
As we know, in Java, a block is delimited by curly braces, {}
, and these code blocks are no different. What is different about instance and static
code blocks is where these blocks appear – in other words, their scope. Both of these code blocks appear outside every method but inside the class.
We will discuss each in turn and then present a code example to demonstrate them in operation. We will start with instance blocks.
Instance blocks
An instance block is a set of braces that appear outside of any method but inside the class. Assuming an instance block is present in a class, every time an object is created (using new
), the instance block is executed. Note that the instance block executes before the constructor. To be technically accurate, super()
is executed first so that the parent constructor has a chance to execute; this is followed by the instance block, after which the rest of the constructor executes. Use the “...