Instance Initializer Block in Java

This is another sub-topic under polymorphism in Java. I hope you enjoyed reading Method overloading and Method overriding in Java, which we discussed in the previous article. If you remember we have already discussed static initializer block in static keyword topic, thus, instance initializer block works in the same fashion as static initializer block. Let’s discuss in details below.

What is Instance initializer Block in Java?

Instance initializer block in Java is used to set the values of the instance variables. When an object of the class is created then it initializes instance data members.

Instance initializer block is mainly used when we have to assign some values to instance data members while performing some operations.

It works the same as static block; the difference is instance initializer block can’t set values to static members of the class.

Instance initializer block in java

Sample Program

package my.project;

class InstanceInitializerBlockDemo{  
	int value;  
    
	InstanceInitializerBlockDemo(){System.out.println("value is "+value);}  
   
    {value=10;}  
       
    public static void main(String args[]){  
    	InstanceInitializerBlockDemo i1=new InstanceInitializerBlockDemo();  
    	InstanceInitializerBlockDemo i2=new InstanceInitializerBlockDemo();  
    }      
}  

Some rules to declare Instance initializer block in a Java program

  • The Instance initializer block is placed within the method, constructor and a block
  • It is created when an instance of the class is created
  • When there is Inheritance, then Instance initializer block is invoked after the invocation of the parent class constructor
  • The instance initializer block is executed in the order of their declaration

Sample Program

package my.project;

class InstanceInitializerBlockParent{  
	InstanceInitializerBlockParent(){  
		System.out.println("Parent class contructor");  
		}  
}

class InstanceInitializerBlockDemo extends InstanceInitializerBlockParent{  

    
	InstanceInitializerBlockDemo(){
		super(); 
		System.out.println("Child Class Constructor");
		}  
	
	InstanceInitializerBlockDemo(int value){
		super(); 
		System.out.println("Child Class Constructor: "+value);
		} 
   
    {System.out.println("Child Instance Initializer Block");}  
       
    public static void main(String args[]){  
    	InstanceInitializerBlockDemo i1=new InstanceInitializerBlockDemo();  
    	InstanceInitializerBlockDemo i2=new InstanceInitializerBlockDemo(2);  
    }      
}  

 

In the above program, we see that the constructor of the parent class is invoked first then instance initializer block and then statements of the child class executed.

This was all about one of the important topics which we can’t ignore. Please use the comment section below to share your doubts and queries and do not forget to join our Facebook group for quick updates on Selenium, Java, and Test Automation.

Join Inviul fb group

Leave a Reply