Advertisement
Static Initialization Block | Instance Initialization Block |
---|---|
To define a static initialization block we use the keyword static | No keyword is required to define an instance initialization block. |
A static initialization block loads as soon as a class loads and it is not associated with a call to the constructor of a class for object creation. | An instance initialization block is only executed when there is a call to the constructor
for creating an object. |
Static block can only access static variables and static methods of its class | An instance initialization block can not only access static variables and static methods but also
instance variables and instance methods of the class. |
There is no automatic call to superclass constructor from the static initialization block. | An instance initialization block always makes an automatic call to superclass constructor by calling super()
before executing any other statement in it. |
Static block is called just once during the entire execution of the program when the class loads. | Instance initialization block can run many times, whenever there is a call to the constructor of the class |
class A
{
static char ch='a';
int a=10;
//Static initialization block of A
static
{
System.out.println("Static block runs");
System.out.println("value of static character = "+ ch);
}
//Instance initialization block of B
{
System.out.println("Instance Initialization block runs")
System.out.println("Value of static character = "+ ch);
System.out.println("Value of instance variable = "+ a);
}
public static void main(String... ar)
{
A ob= new A();
}
}
Static Initialization block runs
Value of static character = a
Instance Initialization block runs
Value of static character = a
Value of instance variable = 10
Advertisement
class B
{
//Constructor of B
B()
{
System.out.println("Constructor of B class is called");
}
//Static initialization block of B
static
{
System.out.println("B class is loaded");
}
}
class A extends B
{
//Constructor of A
B()
{
System.out.println("Constructor of class A is called");
}
//Static initialization block of A
static
{
System.out.println("A class is loaded");
}
//Instance initialization block of B
{
//Compiler makes an automatic call to superclass constructor, by calling super() here.
System.out.println("An object of A is being created");
}
public static void main(String... ar)
{
A ob= new A();
}
}
B class is loaded
A class is loaded
Constructor of B class is called
An object of A is being created
Constructor of class A is called
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement