Why does my object see variables that were not provided to it in the constructor?

I have the following code. What is “correct” and which I don’t understand:

private static void updateGUI(final int i, final JLabel label) {
    SwingUtilities.invokeLater( 
        new Runnable() {
            public void run() {
                label.setText("You have " + i + " seconds.");
            }
        }
    );
}

I create a new instance of the Runnable class, and then in the method of runthis instance I use variables labeland i. It works, but I don’t understand why it works. Why the object in question sees the values ​​of these variables.

In my opinion, the code should look like this (and its incorrect):

private static void updateGUI(final int i, final JLabel label) {
    SwingUtilities.invokeLater(new Runnable(i,label) {

        public Runnable(int i, JLabel label) {
            this.i = i;
            this.label = label;
        }

        public void run() {
            label.setText("You have " + i + " seconds.");
        }

    });
}

So, I would give the variables iand the labelconstructor so that the object can access them ...

By the way, in updateGUII use finalup iand label. I think I used finalit because the compiler wanted it. But I do not understand why.

+3
4

final , , . , , .

. , ,

new Runnable() {
  { /* this code is executed */ }

  public void run() {
    // ...
  }
};

, , - ? , , ? , : .

+4

( ). , label . , .

+2
+2

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


All Articles