"this" link 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 } }); } } 

I do not allow this reference link implicitly?

+3
source share
4 answers

Yes, because in an anonymous inner class, you can access it as follows:

 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 for an anonymous ActionListener could, in principle, be called and used by FooButton before the FooButton is fully initialized.

+6
source

Yes, this link eludes the listener. Since this listener is not really an external class, I don't see any problems in it.

Here you can see this slipping away:

 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"); } } 
+7
source

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

+1
source

Yes. this enclosing class is implicitly in a non-stationary anonymous class.

+1
source

Source: https://habr.com/ru/post/1489120/


All Articles