Thursday, July 16, 2009

Java Double Brace Initialization describes one of my favorite Java tricks: double brace initialization. Double brace initialization is an extension of creating an anonymous inner class. The inner brace is a static initialization block. It will get invokes when the object is initialized. lists UI class instantiation as an application for double bracing. It's been ages since I've used Swing for anything, but I remember anonymous inner classes were very helpful for making tweaks to the Swing classes.

For a brief example consider the following

Foo foo = new Foo() {
// static initialization block
// overridden and new methods
public void setBar(int bar) {
if (bar < 0 || bar >100) {
// ignore input that is out of range
} = bar;

Double bracing can be very helpful for writing test code. The static initialization block can set up an object in a state that is relevant to the test and the relevant methods of the class can be overridden to support the test.


Aaron Hall said...

Small correction: the site is, not

Paul Wiedel said...

Aaron, sorry about that. Thank you for the correction.

Unknown said...

Javas Double Brace Instatiation makes it a lot easier to read your source code. For review reasons is that important to you and your colleagues. I think most people only see these advantages if nobody uses them: they would be glad to have them.

A few tips and backgrounds, too: is is about the obstacles and the possibillities with Javas Double Brace Instatiation:

I hope I could help a little.