This is called an instance initializer. The code in the initializer is inserted after the call to the super class constructor and before the rest of the constructor code.
The first operation of any constructor is to invoke a super class constructor. If a constructor is called explicitly, super(...)
, the specified constructor is used. If no constructor is explicitly invoked, the default constructor (with no arguments) is invoked in the super class. If no such constructor exists, it is a compile time error.
After this explicit or implicit constructor invocation, instance initializers are invoked in the order they appear in source code (yes, you can have more than one initializer).
To illustrate, running this program prints
Another constructor
Init 1
Init 2
Test constructor
class Another {
Another() { System.out.println("Another constructor"); }
}
class Test extends Another {
public static void main(String[] args) { new Test(); }
{ System.out.println("Init 1"); }
Test() { System.out.println("Test constructor"); }
{ System.out.println("Init 2"); }
}
The most commonly seen application is in the initalization the "double brace initialization" idiom, where an anonymous inner class is defined, and an instance is created and configured at once. Here's a fairly common example from Swing programming:
JButton popupButton = new JButton(new AbstractAction("Popup") {
{
putValue(Action.SHORT_DESCRIPTION, "Popup a dialog");
}
@Override
public void actionPerformed(ActionEvent evt)
{
popup();
}
});
This could be useful if you have multiple constructors, and need to perform some parameter-less initialization in every constructor. This could be factored into an initialization block.