0
public class ClickButton extends JButton {
   private int clicks = 0;

   public ClickButton() {
    super("0");

    this.addActionListener (e -> {
        ++clicks ;
        this.setText(clicks + "");
        });
   }
}

How is the lambda expression, inside of addActionListener method, able to access the "clicks" field of my class? Is this because, I can consider Lambda-Expression as a very short initialisation of an inner class, which can of course access this field?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Vlad
  • 1
  • 2
  • Well, `clicks` is `this.clicks` and you obviously have access to `this` in the constructor. If your question is why the operation `++clicks` is possible then check out https://stackoverflow.com/q/67065119/12323248. – akuzminykh Jun 11 '22 at 11:59
  • Why do you think it shouldn't be accessible? – Sweeper Jun 11 '22 at 12:02

0 Answers0