Introduction To Initializer Block In Java

Introduction

 
This article explains how initializer blocks work in Java. We discuss the 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 perform 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.
  1. class Car {  
  2.  int cspeed;  
  3.  Car() {  
  4.   System.out.println("Speed of car is " + cspeed);  
  5.  } {  
  6.   cspeed = 350;  
  7.  }  
  8.  public static void main(String args[]) {  
  9.   Car c1 = new Car();  
  10.   Car c2 = new Car();  
  11.  }  
  12. }  
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.
  1. class Car {  
  2.  int cspeed;  
  3.  Car() {  
  4.   System.out.println("invoked constructor");  
  5.  } {  
  6.   System.out.println("involved instance initializer block");  
  7.  }  
  8.  public static void main(String args[]) {  
  9.   Car c1 = new Car();  
  10.   Car c2 = new Car();  
  11.  }  
  12. }  
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.
  1. class Block {  
  2.  Block() {  
  3.   System.out.println("invoked parent class constructor");  
  4.  }  
  5. }  
  6. class InitializerBlkEx extends Block {  
  7.  InitializerBlkEx() {  
  8.   super();  
  9.   System.out.println("invoked constructor of child class");  
  10.  } {  
  11.   System.out.println("involved instance initializer block ");  
  12.  }  
  13.  public static void main(String args[]) {  
  14.   InitializerBlkEx iblk = new InitializerBlkEx();  
  15.  }  
  16. }   
Output
 
fig-3.jpg