简体   繁体   中英

Is it dangerous to instantiate an inner class within the outer class's constructor? (Java)

I'm currently learning to use Swing. For relatively simple projects at least, it seems natural to either instantiate the components directly in the constructor, or in helper methods called by the constructor. I'm having to use ActionListener fairly often, and I'm often tempted to add them to the components right after they're constructed, especially for actions that only require one or two lines of code. But I'm also nervous about doing so, because instances of non-static nested classes have an implicit reference to the outer instance, and I would assume that instantiating them in constructors carries the same dangers as "leaking this ". However, I've seen some examples of people doing it, and they seemed to know what they were doing, and even the examples on Java's website do something similar:

public class ButtonDemo extends JPanel
                    implements ActionListener {
protected JButton b1, b2, b3;
// ...
b1.addActionListener(this);
b3.addActionListener(this);
// ...

It's not exactly the same thing, but I would think it would carry the same dangers.

Here's an example from my code:

private class DisplayUpdater
{
    private long startTime;    // in milliseconds
    private int elapsedTime;    // in seconds
    private int millisRemaining;
    private Timer timer;

    DisplayUpdater()
    {
        elapsedTime = 0;
        millisRemaining = 1000;
        timer = new Timer(millisRemaining, new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                elapsedTime++;
                display.setText(String.format("%d:%d", elapsedTime / 60, elapsedTime % 60));
            }
        });
        startTime = System.currentTimeMillis();
    }

Are there certain circumstances where doing this is okay? I would naturally assume that I should avoid it if possible, but I'm unsure. Answers, advice, etc. would be greatly appreciated.

This is fine and safe to do. It's known as a lambda expression or anonymous function. It helps to keep your code clean and readable.

It can also make your code adaptable and easy to add to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM