Code Snippet:
class InitDemo { static int y; int x; //Static Initialization Block static { y=10; } // Instance Initialization Block { x=20; } }
Instance initializer block:
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.
Why use instance initializer block?
Suppose I have to perform some operations while assigning value to instance data member e.g. a for loop to fill a complex array or error handling etc.
//Program of instance initializer block that initializes values to the instance variable class Car{ int speed; Car(){ System.out.println("speed is "+speed); } { speed = 120; } public static void main(String args[]){ Car c1=new Car(); Car c2=new Car(); } }
There are three places in java where you can perform operations:
Flow of invoked of instance initializer block & constructor
class Car{ int speed; Car(){ System.out.println("constructor is invoked"); } { System.out.println("instance initializer block invoked"); speed = 120; } public static void main(String args[]){ Car c1=new Car(); Car c2=new Car(); } }
In the above example, it seems that instance initializer block is firstly invoked but NO. Instance intializer block is invoked at the time of object creation. The java compiler copies the instance initializer block in the costructor after the first statement super(). So firstly, constructor is invoked. Let’s understand it by the figure given below
Rules for instance initializer block :
There are mainly three rules for the instance initializer block. They are as follows:
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…