Initializer Block in Java
Initializer Block in Java
Initializer block always executed whenever an instance is created. It is used to declare or initialize the common part of various constructors of a class.
We can note that the contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents).No matter how many constructor you are created in a class. Always Initializer Block run first.
For example,
import java.io.*; public class InitializerBlock{ // Initializer block starts.. { // This code is executed before every constructor. System.out.println("Common part of constructors invoked !!"); } // Initializer block ends public InitializerBlock(){ System.out.println("Default Constructor invoked"); } public InitializerBlock(int x){ System.out.println("Parametrized constructor invoked"); } public static void main(String arr[]){ InitializerBlock obj1, obj2; obj1 = new InitializerBlock(); obj2 = new InitializerBlock(0); } } |
Output:
Common part of constructors invoked!! Default Constructor invoked Common part of constructors invoked!! Parametrized constructor invoked
We can note that the contents of initializer block are executed whenever any constructor is invoked (before the constructor’s contents).No matter how many constructor you are created in a class. Always Initializer Block run first.
The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor.
post a comment