Using the initialization block in Java “double-{“

...
Raphaël ParréePublished on

Using the class initialisation block can help tremendously in initialising objects, take a look at the following code:

JMenuItem menuItem = new JMenuItem("My Menu Item");
menuItem.setMnemonic('M');
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.ALT_MASK));
myMenu.add(menuItem);
menuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        // etc etc
    }
});

This can be also written as:

myMenu.add(new JMenuItem("My Menu Item") \{{
    setMnemonic('M');
    setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, InputEvent.ALT_MASK));
    addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
          ...
        }
    });
}});

This is sometimes referred to as the "double-{" initialisation block, but is merely just extending the JMenuItem using an anonymous class and adding the object initialisation block to that (recall there is also a static initialisation block in classes: static {...}