Instance Initializer Block
Instance Initializer Block
com
http://www.javatpoint.com/instance-initializer-block
Que) What is the use of instance initializer block while we can directly assign a value in
instance data member? For example:
1. class Bike{
2.
int speed=100;
3. }
int speed;
3.
Bike7(){System.out.println("speed is "+speed);}
4.
{speed=100;}
5.
6.
7.
8.
9. }
Test it Now
Output:speed is 100
speed is 100
There are three places in java where you can perform operations:
1. method
2. constructor
3. block
1/4
int speed;
3.
Bike8(){System.out.println("constructor is invoked");}
4.
5.
6.
7.
8.
9. }
Test it Now
Output:instance initializer block invoked
constructor is invoked
instance initializer block invoked
constructor is invoked
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
constructor after the first statement super(). So firstly, constructor is invoked. Let's understand it by the
figure given below:
Note: The java compiler copies the code of instance initializer block in every
constructor.
2/4
3/4
4/4