This code block is executed per instance i.e. it has access to instance methods, fields etc.
It is executed after the constructor hierarchy of that class has been executed but before that class' constructor.
Thus you have to be careful what data you access in there.
Example:
class Foo {
protected String name;
{
System.out.println("Foo's name: " + name);
}
public Foo(String n) {
name = n;
System.out.println("constructing Foo");
}
}
class Bar extends Foo {
{
System.out.println("Bar's name: " + name);
}
public Bar(String n) {
super(n);
System.out.println("constructing Bar");
}
}
If you now create a new Bar
instance using new Bar("baz");
, you would see this output:
Foo's name: null
constructing Foo
Bar's name: baz
constructing Bar
As you can see, the execution order of this is:
Foo
initializer block
Foo
constructor
Bar
initializer block
Bar
constructor