Why my object sees variables which were not given to it in the constructor?
- by Roman
I have the following code. Which is "correct" and which I do not 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 run method of this instance I use variables label and i. It works, but I do not understand why it work. Why the considered object sees values of these variables.
According to my understanding the code should look like that (and its wrong):
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 i and label variables to the constructor so the object can access them...
By the way, in the updateGUI I use final before the i and label. I think I used final because compiler wanted that. But I do not understand why.