Instance Initializer Block:
There are two types of data members: static and instance data members.
Instance data members are those that belongs to instance of a class. i.e objects. Here comes the role of instance initializer block. It is used to give the initial values to the instance data members of the class and the block is executed each time when an object is created.
There are other ways also to initialize the instance data members of class but by using this way , you can perform some additional operation like calculations and other things on the instance data members.
Let us seethe very basic example of this:
class Demo{
Demo(){System.out.println("Inside contructor");}
{System.out.println("Inside block");}
public static void main(String args[]){
Demo d=new Demo();
}
}
Output:
Inside Block
Inside constructor
Let us see another example to assign value:
class Demo{
int i=0;
Demo(){System.out.println("Value of i is" +i);}
{i=20;}
public static void main(String args[]){
Demo d=new Demo();
Demo d1=new Demo();
}
}
Output:
Value of i is 20
Value of i is 20
What actually happens. It seems like the block is executed before the creation of object but that is not the case. Virtually the statements which are placed inside the instance initializer block are placed inside the constructor before the other statements. i.e just following the super() keyword. super() is the first one inside the constructor and after that this block comes.
You can say it is virtually copy pasted inside the constructor after the super() keyword.
So thats why it is invoked at each object creation since on creation of every object constructor is invoked.
0 Comment(s)