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:
Why instance block?
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