mre
mre

Reputation: 44250

"this" reference escaping during construction?

If I do the following,

final class FooButton extends JButton{
    FooButton(){
        super("Foo");
        addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                // do stuff
            }
        });
    }
}

am I letting the this reference implicitly escape?

Upvotes: 3

Views: 954

Answers (4)

JB Nizet
JB Nizet

Reputation: 691933

Yes, the this reference escapes to the listener. Since this listener is not really an external class, I don't see any problem with it, though.

Here's where you could see that this escapes:

final class FooButton extends JButton{
    Foo(){
        super("Foo");
        addActionListener(new ActionListener(){
            private buttonText = FooButton.this.getText(); // empty string

            @Override
            public void actionPerformed(ActionEvent e){
                // do stuff
            }
        });
        this.setText("Hello");
    }
}

Upvotes: 7

Jesper
Jesper

Reputation: 206896

Yes, because in the anonymous inner class you could access it like this:

final class FooButton extends JButton {
    Foo() {
        super("Foo");
        addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                FooButton button = FooButton.this;
                // ... do something with the button
            }
        });
    }
}

The code of the anonymous ActionListener could in principle be called and use the FooButton before the FooButton object is fully initialized.

Upvotes: 6

Peter Lawrey
Peter Lawrey

Reputation: 533660

Yes. this of the enclosing class is implicitly in an non-static anonymous class.

Upvotes: 1

artbristol
artbristol

Reputation: 32427

Yes, the anonymous inner class of ActionListener has a reference to this.

Upvotes: 1

Related Questions