1

Possible Duplicate:
Cannot refer to a non-final variable inside an inner class defined in a different method

I'm just experimenting and have a question.

Why is this acceptable when I am accessing a non-final class variable from an anonymous inner class:

static JLabel e = new JLabel("");
    public static void main(String[] args) {

        JButton b = new JButton("ok");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                String l = e.getText();

            }

        });

    }

But the following is not acceptable without the final modifier:

Community
  • 1
  • 1
mark
  • 2,841
  • 4
  • 25
  • 23
  • 1
    What exactly is the question? Why did the designers of java chose to allow access only to final variables? – amit May 09 '12 at 21:57
  • 1
    I think he's asking why he can access this particular non-final object, but not another. Unless I'm mistaken (entirely possible) it's because the getText() is returning a String, which is immutable (and thus implicitly final). – Charles May 09 '12 at 22:01

3 Answers3

3

Because the class variable is static.

blang
  • 2,090
  • 2
  • 18
  • 17
2

I modified the class a little below. Hopefully this can help you see the answer.

e.getText() in the original code is just shorthand for SomeClass.e.getText() in the below code. Any class in the same package as SomeClass could make a similar reference to e..

On the other hand, other classes in the same package as SomeClass can not refer to args.

class SomeClass {
    static JLabel e = new JLabel("");
    public static void main(String[] args) {

        JButton b = new JButton("ok");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                String l = SomeClass.e.getText();

            }

        });

    }
}
emory
  • 10,725
  • 2
  • 30
  • 58
-2

I answered this question to someone else a few days ago

The answer is that args is out of your scope context. If its not final, it could have changed by the time your actionPerformed method gets called. In that case, you are treating args as a place on another stackframe that may or may not still exist - this is definitely a no no in Java. When you declare args final, it can copy over the variable into your inner class

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80