Java Instance Initializer block

    Instance Initializer block

    This block will allow you to initialize the data member instance. This block will get executed every time the class object is created. You can initialize the instance variable directly but some extra steps will be required to initialize the instance variable within the instance initializer block.

    Example without initializer block-

    class Scooter{  
        int speed=100;  
    }  

    Example with Initializer block-

    class Scooter{  
    
        int speed;  
    
        Scooter(){System.out.println("speed is "+speed);}  
    
        {speed=150;}    
    
        public static void main(String args[]){  
            Scooter b1=new Scooter();  
           Scooter b2=new Scooter();  
        }      
    }  

    Output-

    speed is 150
    speed is 150

    The initializer block is used when we have to person some action while assigning value to the instance data member.

    In Java, these operations can be performed within the method, constructor and block.

    How initializer block works with constructor

    In the below example, we have created a constructor and the initializer block. We will get to know which will execute when.

    Example-

    class Scooter{  
    
        int speed;  
    
          
    
        Scooter(){System.out.println("speed ");}  
    
       
    
        {System.out.println("race ");}  
    
           
    
        public static void main(String args[]){  
            Scooter b1=new Scooter();  
            Scooter b2=new Scooter();  
    
        }      
    }  

    Output-

    race
    speed

    It seems that the initializer block is executed first but this is not the case, the compiler will copy the initializer block in the constructor. Thus the compiler will get invoked first with the object creation.

    Instance initializer block rules-

    • The block is created with object creation.
    • This block will get invoked after the parent’s class constructor.
    • This block will get executed in the order where they appear.

    Instance initializer block invoked after super()

    Example-

    class A{  
        A(){  
           System.out.println("parent class constructor");  
         }  
    }  
    
    class B2 extends A{  
          B2(){  
             super();  
             System.out.println("child class constructor");  
           }     
          {System.out.println("instance initializer block");}  
        
           public static void main(String args[]){  
               B2 b=new B2();  
            }  
           } 
     }

    Output-

    parent class constructor
    
    instance initializer block
    
    child class constructor