3

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?

Jk1
  • 11,233
  • 9
  • 54
  • 64
mre
  • 43,520
  • 33
  • 120
  • 170

4 Answers4

7

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");
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
6

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.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • what is the official name of " FooButton.this" kind of construct ? – Geek Feb 08 '13 at 16:08
  • 1
    @Geek, [Qualified this](http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.8.4) – mre Jul 12 '13 at 12:32
1

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

artbristol
  • 32,010
  • 5
  • 70
  • 103
1

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

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130