2017  Kodetalk | Feedback | Privacy Policy | Terms | About
userimage

Why use instance initializer block?

Why use instance initializer block?
userimage
Instance Initializer block is used to initialize the instance data member. It run each time when object of the class is created. The initialization of the instance variable can be directly but there can be performed extra operations while initializing the instance variable in the instance initializer block.
userimage

Below some points and example will help you to understand in a simpler way,


  • Instance initializers are block of code with out any keyword keyword. The code which needs to be initialized will be put inside the braces {}. These are executed when the instance is created for the first time by any application.
  • Static and instance variables can be initialized inside instance blocks.
  • Any number of instance blocks can be defined, that will be executed in the order of definition. Instance initializer blocks will be executed after the static initializer blocks.
  • Instance and static methods can be called from the instance initializers.
  • Instance blocks are used for initializing the instance variables at the time of creating the instance of that class.

Lets look at the simple example snippet shows how to use the instance initializer.


package com.test.coreinstance;

/**
 * Java Instance Initializer Example
 *
 * @author Rahul Kumar
 *
 */
public class JavaInstanceInitializerExample {

    // Static variable
    static int j = 0;

    // Instance variable
    int i = 0;

    {
        System.out.println("Instance Initializer Called");
        i = 0; // instance variable can be initialized
        j = 10; // Initialize static variable
        instanceMethod();
    }
    static {
        System.out.println("Static Initializer Called");
        testMethod();// Can invoke static method, not instance methods
    }

    // Static method
    public static void testMethod() {
        System.out.println("Static 'testMethod()' called");
    }

    // Static method
    public static void instanceMethod() {
        System.out.println("Instance 'instanceMethod()' called");
    }

    public static void main(String[] args) {
        System.out.println("J Value Before Instance Initializer Called : " + j);
        new JavaInstanceInitializerExample();
        System.out.println("J Value After Instance Initializer Called : " + j);
    }
}


If you look at the above code, the order of executing the blocks are clear. Also note that variable “j” is not initialized untill the instance initializer is invoked.


Result :


Static Initializer Called
Static 'testMethod()' called
J Value Before Instance Initializer Called : 0
Instance Initializer Called
Instance 'instanceMethod()' called
J Value After Instance Initializer Called : 10


Answer is