The Initializer Block in Java
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:
Tip: If we want to execute some code once for all objects of a class then we will be using Static Block in Java
Speed of Car: 60
Common 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 firstname.lastname@example.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.
Please Login to comment...