“this” reference escaping during construction?

前端 未结 4 2058
无人共我
无人共我 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:52

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

提交回复
热议问题