Sunday, 10 November 2019

SE - 38 - Static Initialisation block.Vs Instance Initialisation block vs Constructor

The order in which the Static Initialisation block ,  Instance Initialisation block and Constructors are called is as below:

1) Static Initialisation block - This is called when memory is allocated , so this one is called very first. If there are multiple blocks then it is called in the order they are written.

2) Instance Initialisation block - This is called before the Constructors.If there are multiple blocks then it is called in the order they are written.

3) Constructors : Constructors are called at last.

Lets quote an example to clearly understand difference between these 2 type of blocks:

public class Test 
 { 
     public static void main(String[] args) 
     { 
         A a = new A(); 
     } 
 } 
   
class A 
{ 
  
//first static initialization block
static {
 System.out.println("Static-1");
}

//first Instance Initialization bloc
{
 System.out.println("Init-1");
}

//Constructor
A(){
 System.out.println("constructor");
}

//second static initialization block
static {
 System.out.println("Static-2");
}

//second Instance Initialization bloc
{
 System.out.println("Init-2");
}} 


Output : 
Static-1
Static-2
Init-1
Init-2
constructor

So here we can see that Static blocks are called first in the order they were written , then instance blocks were called and at last constructors were called.


No comments:

Post a Comment