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:
解决方案
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();
}
});
}
}