Introduction To Initializer Block In Java

Introduction

This article explains how initializer blocks work in Java. We discuss instance initializer blocks in Java.

Description

An initializer block in Java initializes the instance data members. It runs each time an object of a class is created. We can directly initialize instance variables but they can also be used to performed some extra operations.

Advantages over directly assigning an instance data member

Suppose we must perform other operations while assigning a value to an instance data member.

Example:

  1. used in error handling
  2. a for loop to fill a complex array etcetera

Example

In this example, show the instance initializer block how to perform initialization.

class Car

  {

    int cspeed;

    Car()

      {

        System.out.println("Speed of car is " +cspeed);

      }

      {

        cspeed=350;

      }

    public static void main(String args[])

      {

        Car c1=new Car();

        Car c2=new Car();

      }

  }

Output

fig-1.jpg

Java provides the following three ways to perform operations:

  1. constructor
  2. method
  3. block

The following sample code shows who invoked the first constructor or block; it looks at whether an instance initializer block is invoked first but no instance initializer block is used at the time of object creation. The Java compiler copies the instance initializer block in the constructor after the first statement super(). So first, the constructor is invoked.

class Car

  {

    int cspeed;

    Car()

      {

        System.out.println("invoked constructor");

      }

      {

        System.out.println("involved instance initializer block");

      }

    public static void main(String args[])

      {

        Car c1=new Car();

        Car c2=new Car();   

      }

  }

Output

fig-2.jpg

Rules for instance initializer blocks

Some main rules for the initializer block are:

  1. run every time a class instance is created
  2. run after the constructor's call to super().
  3. is created when instance of the class is created.
  4. comes in the order in which they appear.

Program

After super() the instance initializer block is invoked.

class Block

  {

    Block()

      {

        System.out.println("invoked parent class constructor");

      }

  }

class InitializerBlkEx extends Block

  {

    InitializerBlkEx()

      {

        super();

        System.out.println("invoked constructor of child class");

      }

      {

        System.out.println("involved instance initializer block ");

      }

    public static void main(String args[])

      {

        InitializerBlkEx iblk=new InitializerBlkEx();

      }

  }

Output

fig-3.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all