In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created.
The initializer block contains the code that is always executed whenever an instance is created and it runs each time when an object of the class is created. There are 3 areas where we can use the initializer blocks:
- Constructors
- Methods
- Blocks
Tip: If we want to execute some code once for all objects of a class then we will be using Static Block in Java
Example 1:
Java
class Car {
int speed;
Car()
{
System.out.println( "Speed of Car: " + speed);
}
{
speed = 60 ;
}
public static void main(String[] args)
{
Car obj = new Car();
}
}
|
Example 2:
Java
import java.io.*;
public class GFG {
{
System.out.println(
"Common part of constructors invoked !!" );
}
public GFG()
{
System.out.println( "Default Constructor invoked" );
}
public GFG( int x)
{
System.out.println(
"Parameterized constructor invoked" );
}
public static void main(String arr[])
{
GFG obj1, obj2;
obj1 = new GFG();
obj2 = new GFG( 0 );
}
}
|
OutputCommon part of constructors invoked !!
Default Constructor invoked
Common part of constructors invoked !!
Parameterized constructor invoked
Note: The contents of the initializer block are executed whenever any constructor is invoked (before the constructor’s contents)
The order of initialization constructors and initializer block doesn’t matter, the initializer block is always executed before the constructor.
For more details about the Instance Initialization in Java, refer to the article Instance Initialization Block (IIB) in Java
This article is contributed by Ashutosh Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.