Feb 21, 2005

Pattern Patter: Anonymous Subclass with Instance Initializer

In JUnit Recipes, JB Rainsberger points out this idiom:

static final Set s = new HashSet() {{

(JB points to an article by Paul Holser, which cites Dave Astels’ Test-Driven Development as the source.)

What’s it do? The new HashSet(){}; part creates an anonymous subclass (a new type of HashSet without any name). The inner braces are an instance initializer, run before the constructor (implicit and empty) of our new class. So this code creates a new Set, and fills its contents.