Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - As Method or Inner Class or Class?

So I've stumbled across several ways of implementing an ActionListener and I'm wondering if someone can walk me through the differences of how each works and whether there are reasons or advantages to use one over the other?

The first is below in a block of code:

public void actionPerformed(ActionEvent arg0) {
// CODE HERE
}

The second way I saw was within another block of code as:

private class myListener implements ActionListener {
// CODE HERE
}

The third was is simply having a separate class for the ActionListener, with similar code to that above, but within a separate class.

I'm wondering whether the method approach is more efficient as new objects don't have to be created for each, you simply reference this as the ActionListener rather than, for example, referencing new myListener(). Thank you.

like image 441
mino Avatar asked Jan 17 '23 05:01

mino


2 Answers

There's no difference in speed in any of the options; you'll always have an object that implements the ActionListener interface. Avoiding an instance of a separate class will just save you a few bytes of memory.

Your choice really should be based on what makes sense for your code, structurally. For example, having your public class implement ActionListener may look weird for those who are using that class, especially if the ActionListener behavior is supposed to be private to the class and not used outside it.

So it's mostly a choice of what you think looks better in your code; the only real difference will be with regards to field / method access (e.g. a separate, non-inner class won't have access to private methods and fields of your class, an anonymous inner class can't access non-final variables of the enclosing method, etc).

like image 105
vanza Avatar answered Jan 21 '23 15:01

vanza


I don't like or use "implements ActionListener".

I do like and use anonymous inner classes like:

    btnPurplescreen.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Color baseColor = Color.BLUE;
            panelImage.setBackground(baseColor);
            panelReference.setBackground(baseColor);
            panelReference2.setBackground(baseColor);
            baseType = BaseType.PURPLE;
        }
    });
like image 45
Java42 Avatar answered Jan 21 '23 14:01

Java42