In additional to @Bohemian's answer.
If you have multiple constructors an intialiser block avoid duplication.
public class A {
final Map map = new HashMap(); {
// put things in map.
}
final int number; {
int number;
try {
number = throwsAnException();
} catch (Exception e) {
number = 5;
}
this.number = number;
}
public A() { /* constructor 1 */ }
public A(int i) { /* constructor 2 */ }
}
What about normal classes for which non-static blocks run everytime before the constructor?
Technically the order is
- the super constructor is always called first
- all the initializer blocks in order of appearence.
- the constructor code
In reality all this code is in the byte code for each constructor so there is nothing before or after the constructor at runtime.
Before there is any more confusion as to the order of initialization
public class Main extends SuperClass {
{
System.out.println("Initialiser block before constructor");
}
Main() {
System.out.println("Main constructor");
}
{
System.out.println("Initialiser block after constructor");
}
public static void main(String... args) {
new Main() {{
System.out.println("Anonymous initalizer block");
}};
}
}
class SuperClass {
SuperClass() {
System.out.println("SuperClass constructor");
}
}
prints
SuperClass constructor
Initialiser block before constructor
Initialiser block after constructor
Main constructor
Anonymous initalizer block