“this” reference escaping during construction?

前端 未结 4 2056
无人共我
无人共我 2020-12-07 04:07

If I do the following,

final class FooButton extends JButton{
    FooButton(){
        super(\"Foo\");
        addActionListener(new ActionListener(){
               


        
4条回答
  •  一个人的身影
    2020-12-07 04:39

    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.

提交回复
热议问题