Java.Core.Why do we need instance blocks if we have constructor ?

Why Do We Need Instance Initialization Blocks (IIB) If We Have Constructors?

Instance Initialization Blocks (IIB) are not strictly necessary, but they provide some benefits over constructors in certain cases. Here’s why:


1. To Avoid Code Duplication in Multiple Constructors

If a class has multiple constructors, an instance block helps initialize common fields without repeating code in each constructor.

Example Without Instance Block (Code Duplication)

class Example {
    int x, y;

    Example() {
        // Common initialization
        x = 10;
        y = 20;
        System.out.println("Default Constructor");
    }

    Example(int a) {
        // Same initialization repeated
        x = 10;
        y = 20;
        System.out.println("Parameterized Constructor: " + a);
    }

    void display() {
        System.out.println("x: " + x + ", y: " + y);
    }

    public static void main(String[] args) {
        new Example().display();
        new Example(5).display();
    }
}

Problem

  • The initialization code (x = 10; y = 20;) is duplicated in both constructors.
  • If we need to modify initialization logic, we must update every constructor.

Example Using an Instance Block (Avoids Duplication)

class Example {
    int x, y;

    // Instance Initialization Block (runs before any constructor)
    {
        x = 10;
        y = 20;
        System.out.println("Instance Block Executed");
    }

    Example() {
        System.out.println("Default Constructor");
    }

    Example(int a) {
        System.out.println("Parameterized Constructor: " + a);
    }

    void display() {
        System.out.println("x: " + x + ", y: " + y);
    }

    public static void main(String[] args) {
        new Example().display();
        new Example(5).display();
    }
}

Output

Instance Block Executed
Default Constructor
x: 10, y: 20
Instance Block Executed
Parameterized Constructor: 5
x: 10, y: 20

The initialization code is written only once in the instance block.
Instance block executes before each constructor, ensuring x and y are always initialized.


2. Runs Before Constructors, Even If Constructor Calls super()

  • When a constructor calls super(), the superclass constructor runs before the subclass constructor.
  • However, instance blocks in the subclass execute before its constructor, ensuring initialization happens before constructor execution.

Example

class Parent {
    Parent() {
        System.out.println("Parent Constructor");
    }
}

class Child extends Parent {
    int x;

    // Instance block runs **before** Child's constructor
    {
        x = 100;
        System.out.println("Instance Block in Child");
    }

    Child() {
        System.out.println("Child Constructor");
    }

    public static void main(String[] args) {
        new Child();
    }
}

Output

Parent Constructor
Instance Block in Child
Child Constructor

Even though super() runs first, the instance block runs before the Child constructor.
This ensures that instance variables in Child are initialized before the constructor executes.


3. Useful for Complex Object Initialization

If object initialization requires multiple steps or conditions, an instance block can help simplify the process.

Example: Initializing an Array in an Instance Block

class Example {
    int[] numbers;

    // Instance block initializes the array
    {
        numbers = new int[5];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = i * 10;
        }
        System.out.println("Instance Block: Array Initialized");
    }

    Example() {
        System.out.println("Constructor Called");
    }

    void display() {
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        new Example().display();
    }
}

Output

Instance Block: Array Initialized
Constructor Called
0 10 20 30 40 

✔ The instance block ensures the array is initialized properly before the constructor runs.


Final Thoughts

FeatureInstance BlockConstructor
Runs before constructor?✅ Yes❌ No
Reduces code duplication?✅ Yes❌ No (if multiple constructors exist)
Handles common initialization?✅ Yes✅ Yes
Runs every time an object is created?✅ Yes✅ Yes
Used in inheritance before constructor?✅ Yes❌ No

When to Use Instance Blocks?

✔ If you have common initialization logic across multiple constructors.
✔ If initialization must happen before the constructor runs.
✔ If the constructor calls super(), but you need subclass fields initialized first.
✔ If initialization is complex (e.g., setting up arrays, collections, or dependent values).

This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.