If you want to initialize an instance variable you will put that code in a constructor. In this post we'll see one alternative to using a constructor that can be used to initialize instance variables which is called initializer block in Java.
Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword.
General form of Initializer block in Java
{ // whatever code is needed for initialization // goes here }
Usage of Initializer block in Java
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors. If you have some common code that you want to be executed regardless of which constructor is used, that code can be put in an initializer block in Java.
Initializer block Java Example
public class InitBlockDemo { // no-arg constructor InitBlockDemo(){ System.out.println("no-arg constructor invoked"); } // constructor with one param InitBlockDemo(int i){ System.out.println("constructor with one param invoked"); } // initializer block { System.out.println("This will be invoked for all constructors"); } public static void main(String[] args) { InitBlockDemo ibDemo = new InitBlockDemo(); InitBlockDemo ibDemo1 = new InitBlockDemo(10); } }
Output
This will be invoked for all constructors no-arg constructor invoked This will be invoked for all constructors constructor with one param invoked
Here it can be seen that the code with in the initializer block is copied in every constructor and that code is executed when the constructor of the class is called.
That's all for this topic Initializer Block in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Basics Tutorial Page
Related Topics
You may also like-
This sentence is wrong "Here it can be seen that initializer block is called first before calling the constructor of the class.".
ReplyDeleteInitializer block always gets called after calling the constructor only.
Thanks for pointing it out... I'll re-frame it what I meant was code to print in initializer block is called first when the constructor is called but what I have actually written is giving the wrong impression..
DeleteIn the line above it I did mention "The Java compiler copies initializer blocks into every constructor."
Many Thanks for pointing it out..
Your welcome!!
DeleteFor better understanding, you should give an example which creates a base class with a constructor printing something & extend it. Now call base class constructor via super keyword, you will see that after super(); keyword only, your initializer block gets executed. This will prove the words "The Java compiler copies initializer blocks into every constructor."
Something like
InitBlockDemo(){
super();
System.out.println("no-arg constructor invoked");
}
But thanks for the tutorials which are excellent presented in a brilliant way.