Advertisement
//Java - Static initialization block
class A
{
//Static Initializaton Block
static
{
System.out.println("Hello from the static block");
}
public static void main(String... ar)
{
}
}
Hello from the static block
//Java - Static initialization block can only access static variable of a class
class A
{
static int i;
static //static initialization block
{
i=10;
System.out.println("A class is loaded");
System.out.println("value of i = "+ i);
}
public static void main(String... ar)
{
}
}
A class is loaded
value of i = 10
Advertisement
//Java - Static initialization block cannot access instance variables
class A
{
int a=20;
static //static initialization block
{
System.out.println("A class is loaded");
System.out.println(a);
}
public static void main(String... ar)
{
}
}
A.java:8: error: non-static variable a cannot be referenced from a static context
System.out.println(a);
^
1 error
//Java - Multiple static initialization blocks.
class A
{
//first static initialization block
static
{
System.out.println("First hello from static block");
}
public static void main(String... ar)
{
}
//second static initialization block
static
{
System.out.println("Second hello from static block");
}
//third static initialization block
static
{
System.out.println("Third hello from static block");
}
}
First hello from static block
Second hello from static block
Third hello from static block
//Java - Static initialization block in inheritance
class B
{
static //static initialization block of A
{
System.out.println("Static block of B");
}
}
class A extends B
{
static //static initialization block of B
{
System.out.println("Static block of A");
}
public static void main(String... ar)
{
}
}
Static block of B
Static block of A
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement