Java Instance Initializer Block


To initialize the instance variables which is called Instance initializer block. It is invoked every time an object is created.

 

Instance initializer blocks are executed before constructors are invoked.

 

Initialization blocks are placed above the constructors within curly braces.

 

The parent class constructor is invoked before the instance initializer block is invoked.


Syntax:

 public class Car{
     
    //This is initializer block 1
    {
      //statements
    }
 
    //This is initializer block 2
    {
      //statements
    }
} 

Example:

 class Car{ 
	int speed;    
    Car()
    {
    	System.out.println("Car speed is "+speed);
    }  
    {speed=500;} 
}
public class Instanceinitializerblock
{  
	public static void main(String args[])
    {  
    	Car c=new Car();  
    	Car c=new Car();  
    }      
} 

Example:

Instance initializer blocks are executed before constructors are invoked.

 class Car{ 
	int speed;    
    Car()
    {
    	System.out.println("Constructor");
    }  
    {	System.out.println("Instance Initializer block");	} 
}
public class Instanceinitializer
{  
	public static void main(String args[])
    {  
    	Car c=new Car(); 
    }      
} 



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.