Using the initialization block in Java “double-{“

2011-02-15

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 {...}

This article does not necessarily reflect the technical opinion of EDC4IT, but purely of the writer. If you want to discuss about this content, please use thecontact ussection of the site