This question already has an answer here:
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
Static block gets executed when the class is loaded into JVM whereas constructor block gets executed when an instance is created.
A static initializer is the equivalent of a constructor in the static context. You will certainly see that more often than an instance initializer.
You need to know that
super(params)
or if you want to use default constructorsuper()
. In case of default constructor you don't have to write it explicitly.super(...)
callSo classes are compiled into classes similar to this.
To be able to execute
main
method fromSon
class JVM needs to load code of this class (and classes it extends). After class is fully loaded JVM initialize its static content which involves executing static blocks (yes, there can be more then one static blocks in one class). To fully loadSon
class JVM needs to know details about its parent class so it will fully loadParent
class beforeSon
which means it will also execute its static blocks before static blocks inSon
class.So output will look like:
Parent static block
Son static block
Now in
main
method you are invokingSon
class constructor vianew Son()
which code looks likeSince its
super()
refer toParent
class constructor, which isas result you will see
Parent initializer block
Parent constructor
This handles
Parent#constructor()
executed withsuper()
so next you will see code from Son constructor aftersuper()
which will generateSon initializer block
Son constructor
To see that classes will be loaded even before you use
Son
constructor or evenmain
method you can just print something before usingSon
constructor likewhich will result in
Static block called when your class is loaded and your class is first loaded by classloader in jvm so first they get executed
then you create object so your parent init block is called then your parent constructor due to constructor chaining in java then derived class init block then derived class constructor