I know that static blocks are initialized at the time the class is loaded and since the class is loaded only once in a program,they are initialized only once.
IIB (Instance initialization blocks) are initialized every time an instance of the class is made, and the same for constructors: they are executed during object creation.
I don't understand why in the below program IIB is executed in prior to Constructors. Code-
public class Hello {
public static void main(String args[]) {
C obj = new C();
}
}
class A {
static {
System.out.println("Inside static block of A");
}
{
System.out.println("Inside IIB of A");
}
A() {
System.out.println("Inside NO-ARGS constructor of A");
}
}
class B extends A {
static {
System.out.println("Inside static block of B");
}
{
System.out.println("Inside IIB of B");
}
B() {
System.out.println("Inside NO-ARGS constructor of B");
}
}
class C extends B {
static {
System.out.println("Inside static block of C");
}
{
System.out.println("Inside IIB of C");
}
C() {
System.out.println("Inside NO-ARGS constructor of C");
}
}
Why IIB is executed first compared to constructors?
sysoutis executed after the initialization block, which is inserted as the first statement (aftersuper()) by the compiler. docs.oracle.com/javase/tutorial/java/javaOO/initial.html