Anonymous classes and instance initializers
This is a mixture of two, pretty cool features that makes working with certain APIs (for example the collections API, AWT and Swing) much easier. Most Java programmers probably know about anonymous classes, where you can create a whole new class and an instance of it using only a 'new' operator.
This is an example of some code in Swing using an anonymous subclass:
JButton myButton = new JButton("My Button");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
// do something here
}
});
An instance initializer is probably less well known. I knew about the static initializer for a long time, where you can do this:
static {
// do something here
}
The code inside a static initializer block is run when the class is loaded.
You can also create an instance initializer block like so:
{
// do something here
}
This code is run for every instance of a class that is created.
Mixing these together, you can achieve cool stuff like this:
List words = new ArrayList() {{
add("Hello");
add("World");
}};
Which is a small, concise and useful way of initialiazing a new collections object. I've also seen a few examples where people construct a JPanel like this although I'm sure there are many more uses of this technique.
Comments
Nobody has commented on this post yet.