JAVA

Java Instance Block


What is Instance Block?

In Java, an instance block, also known as an instance initializer, is a block of code within a class that is executed when an instance (object) of the class is created.

Syntax

public class MyClass {
    // Instance block
    {
        // Initialization code
    }

}

Note: 

  • It is similar to method which has no name.
  • It always executed before the constructor.
  • Instance blocks are defined within a class not inside any method.
  • We can use variable only inside the instance block not methods.

Why instance block?

  • We write time consuming code inside a instance block like- JDBC Connectivity.
  • They were developed as a way to provide a common set of actions or initializations that need to be performed for all constructors of a class.

Example

class InstanceBlock {
	int a,b;
	// normal method
	void show() {
		a=10; b=20;
		System.out.println("show method: " + a + " " +b);
	}
	// default-constructor
	InstanceBlock() {
		a=30; b=40;
		System.out.println("Default Constructor: " + a + " " +b);
	}
	// instance block
	{
		a=50; b=60;
		System.out.println("Instace Block: "+ a + " " +b);
	}
}
class calling {
	public static void main(String[] args) {
        InstanceBlock obj = new InstanceBlock (); // instance block will be execute before the default constructor
        obj.show();  // show() method will call after instance block and constructor 
    }
}	

Output:

Instace Block: 50 60
Default Constructor: 30 40
show method: 10 20