Instance Initialization Block is a block used to initialize instance variables or non-static variables in a class i.e., to initialize a state of an object. The Instance Initialization Block executes after the call of the constructor. It gets executed once the class is loaded. It runs whenever the object of the class is created.
The Syntax of the Instance Initialization Block enclosed in the {}
For example :
{
// initialization statements
}
above the Initialization Block is without any name, we can define a Initialization Block in a class as :
class example
{
int i;
{
i = 10;
}
example(int j)
{
i = j;
}
}
class MainClass
{
public static void main(String[] args)
{
example a = new example(50);
System.out.println(a.i);
}
}
In the above code the Initialization block is present in the example class. This block gets executed after the instance of the class is created or after the call of the super(). whenever the constructor is called afterwards the i instance is initialized to 10.
0 Comment(s)