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:
- used in error handling
- 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
Java provides the following three ways to perform operations:
- constructor
- method
- 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
Rules for instance initializer blocks
Some main rules for the initializer block are:
- run every time a class instance is created
- run after the constructor's call to super().
- is created when instance of the class is created.
- 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