Skip to main content

Anonymous subclass with instance initializer

Posted by wwake on February 21, 2005 at 7:26 AM PST

In JUnit Recipes, JB Rainsberger points out this idiom:


static final Set s = new HashSet() {{

  add("this");

  add("that");

  add("another");

}};

(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.

Related Topics >>