An instance block (also called an instance initialization block) is a nameless block of code defined inside a class. It executes every time an object of the class is created, before the constructor is executed.
- Declared inside a class but outside all methods
- Executed once per object creation
- Common logic shared across all constructors
- Executed before the constructor
- Cannot accept parameters
Syntax
class ClassName {
{
// Instance block code
}
}
Example 1: Instance Block with Multiple Constructors
class GFG {
GFG() {
System.out.println("1st argument constructor");
}
GFG(String a) {
System.out.println("2nd argument constructor");
}
GFG(int a, int b) {
System.out.println("3rd arguments constructor");
}
{
System.out.println("Instance block");
}
}
class GFGJava {
public static void main(String[] args) {
new GFG();
new GFG("I like Java");
new GFG(10, 20);
}
}
Output
Instance block 1st argument constructor Instance block 2nd argument constructor Instance block 3rd arguments constructor
Explanation:
- The instance block executes before every constructor call.
- Regardless of which constructor is used, the instance block runs first.
- This ensures shared logic executes uniformly for all object types.
Note: The sequence of execution of instance blocks follows the order- Static block, Instance block, and Constructor.
Example 2: Demonstrating Execution Order
class GFG {
static {
System.out.println("I am Static block!");
}
{
System.out.println("I am Instance block!");
}
GFG() {
System.out.println("I am Constructor!");
}
public static void main(String[] args) {
new GFG();
}
}
Output
I am Static block! I am Instance block! I am Constructor!
Explanation:
- Static block executes once when the class is loaded.
- Instance block executes each time an object is created.
- Constructor executes last to complete object initialization.
Why Use Instance Blocks?
Advantages
- Avoids code duplication across multiple constructors
- Ensures common initialization logic runs for every object
- Useful when multiple constructors require the same setup logic
Limitations
- Cannot accept parameters
- Not suitable for object-specific initialization
- All objects are initialized with the same logic and values
When to Use Instance Blocks
- When common logic must run for all constructors.
- When initialization does not depend on constructor parameters.
- When code reuse across constructors is required.
When to Avoid Instance Blocks
- When initialization requires parameters
- When constructor-specific logic is sufficient
- When readability may be affected due to hidden execution flow