The instance initializer syntax is a special block of code enclosed in curly braces within a class, but outside of methods and constructors. This block is called the instance initializer block. It is executed each time a new object of the class is created, immediately after the parent class constructor is called and before the current class constructor code is executed.
public class Example { { // Instance initializer block System.out.println("Instance initialization"); } private int x; public Example(int x) { this.x = x; System.out.println("Constructor"); } }
Instance initializer is useful for:
What happens if there is both an instance initializer and a constructor in the class? In what order are they executed?
Answer: First, the instance initializer is executed, then the constructor code. If there are multiple instance initializer blocks in the class, they are executed in the order they are defined.
Example:
public class Demo { { System.out.println("Instance initializer 1"); } public Demo() { System.out.println("Constructor"); } { System.out.println("Instance initializer 2"); } } // Output when new Demo(): // Instance initializer 1 // Instance initializer 2 // Constructor
Story
In one project, a developer placed logic in the instance initializer instead of a method or constructor. When inheriting the class and overriding the constructor, the instance initializer still executed, leading to an unexpected initialization order and business logic errors.
Story
In another project, the instance initializer accessed class fields that were initialized lower in the code. It turned out that the variables had not been initialized yet, leading to a NullPointerException when creating an object.
Story
The team added an operation related to external resources (DB) in the instance initializer. As a result, each constructor call established a DB connection, which overloaded the system during batch object creation.