You can use it with an anonymous class:
new MyClass() {
{
// do something extra on construction (after the constructor executes)
}
}
I find this is particularly useful for initializing "look up" maps (ie fixed contents) in place:
Map<String, String> map = new HashMap<String, String>() {
{
put("foo", "bar");
put("one", "two");
// etc
}
};
FYI, this is sometimes (poorly) called "double brace initialization", when in fact it's simply employing an initializer block.
Although such an anonymous class is technically a subclass, the beauty of this is shown when comparing using this technique with a more traditional one in creating an unmodifiable map:
Compare this straightforward one-liner, which places data and assignment together:
private static final Map<String, String> map = Collections.unmodifiableMap(
new HashMap<String, String>() {{
put("foo", "bar");
put("one", "two");
// etc
}});
With this mess, which must create a separate object due to final
only allowing one assignment:
private static final Map<String, String> map;
static {
Map<String, String> tempMap = new HashMap<String, String>();
tempMap.put("foo", "bar");
tempMap.put("one", "two");
// etc
map = Collections.unmodifiableMap(tempMap);
}
Also note that with the mess version, the two statements need not be adjacent, so it can become less obvious what the contents of the unmodifiable map is.