Possible Duplicate:
How is an instance initializer different from a constructor?
When all the required work can be done inside the constructor, then why do we still need non-static block in Java?
EDIT: What about normal classes for which non-static blocks run everytime before the constructor?
In additional to @Bohemian's answer.
If you have multiple constructors an intialiser block avoid duplication.
public class A {
final Map<String, String> map = new HashMap<String, String>(); {
// 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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With