I'll try to explain the calling sequence with an example, but first of all let's consider that if you add the void
access qualifier, this will be a method and not a constructor.
Secondly remember that a class can have two type of initialization block:
- Static Initialization Block
- Instance Initialization Block
The Static Initialization Block will be called first of all and before the constructor, since is at class level and will be execute even before any class instance (i.e. object of that class type) is created. The second, i.e. the Instance Initialization Block is executed as soon as a new instance of the class is created. After that two blocks, it will be called the constructor. You can see it with the following example:
public class MainWithStaticCalls {
{
System.out.println("Init block called");
}
static {
String[] str = {"1", "2"};
System.out.println("Static called");
}
public MainWithStaticCalls() {
System.out.println("this is constructor");
}
void MainWithStaticCalls() {
System.out.println("this is NOT constructor");
}
public static void nope() {
System.out.println("Nope");
}
public static void main(String[] a) {
MainWithStaticCalls.nope();
System.out.println("************");
MainWithStaticCalls obj = new MainWithStaticCalls();
NewClass nc = new NewClass();
nc.callMe();
System.out.println("Main");
}
}
The output is:
Static called
************
Init block called
this is constructor
NewClass: I'm called
Main
If I comment out the "nope
" static call:
public class MainWithStaticCalls {
... // Same thing as above
public static void main(String[] a) {
// MainWithStaticCalls.nope();
System.out.println("************");
MainWithStaticCalls obj = new MainWithStaticCalls();
NewClass nc = new NewClass();
nc.callMe();
System.out.println("Main");
}
}
The result is:
Static called
************
Init block called
this is constructor
NewClass: I'm called
Main
So it is the same result if do not comment out the "nope
" call. This is to show that the static method is called only once, when the class is firstly faced by the JVM. If we instantiate another object:
public class MainWithStaticCalls {
... // Same thing as above
public static void main(String[] a) {
// MainWithStaticCalls.nope();
System.out.println("************");
MainWithStaticCalls obj1 = new MainWithStaticCalls();
MainWithStaticCalls obj2 = new MainWithStaticCalls();
NewClass nc = new NewClass();
nc.callMe();
System.out.println("Main");
}
}
The output is:
Static called
************
Init block called
this is constructor
Init block called
this is constructor
NewClass: I'm called
Main
you see that the Instance Initialization Block is called every time a new object fof that class type is created (as well as the constructor), while the Static Initialization Block is called only once.