i find this example and i want to understand the logic behind it ? how constructors and static blocks and initializer blocks works in inheritance ? in which stage each one is called ?
public class Parent {
static {
System.out.println("i am Parent 3");
}
{
System.out.println("i am parent 2");
}
public Parent() {
System.out.println("i am parent 1");
}
}
public class Son extends Parent {
static {System.out.println("i am son 3");}
{System.out.println("i am son 2");}
public Son() {
System.out.println("i am son 1");
}
public static void main(String[] args) {
new Son();
}
}
the output is :
i am Parent 3
i am son 3
i am parent 2
i am parent 1
i am son 2
i am son 1
A static block is called once, when the class is loaded and initialized by the JVM. An instance initializer is executed when an instance of the class is constructed, just like a constructor.
Static and Instance initializers are described in the Java Language Specification