0

I have a question about why should we set a field final when we use it in an innerclass? for example why should we set the modifier of textField to final? My question is that why it will not be available if we do not declare it as final?

  final TextField textField = new TextField();
    Button b = new Button();
    b.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            textField.setText("hello");
        }
    });
Siavash
  • 503
  • 1
  • 5
  • 25
  • Please refer to Jesper's answer to a similar question - http://stackoverflow.com/questions/1299837/cannot-refer-to-a-non-final-variable-inside-an-inner-class-defined-in-a-differen – Deepak Bala Nov 23 '13 at 10:31
  • see this. then you can clear... http://stackoverflow.com/questions/3910324/why-inner-classes-require-final-outer-instance-variables-java – subash Nov 23 '13 at 10:32
  • If you need possibility to change those values, you can always use `Holder`. – msangel Nov 23 '13 at 10:39

1 Answers1

2

The reason is that the values of the variables accessed from within the anonymous class are copied. If the variable could be modified from outside the class, this would produce a stale (out of date) value, which could affect the program's correctness and produce unexpected results. Java avoids this issue by enforcing you to declare those variables as final and thereby unmodifiable.

Lefteris Laskaridis
  • 2,292
  • 2
  • 24
  • 38
  • I cannot understand why does it affect on program's correctness? As you said the field will be copied, thus we use two different fields and what is the problem if we change the field's value from outside the inner class or from inner class? – Siavash Nov 23 '13 at 10:48
  • 1
    The underlying intention is to access the value of the variable from within the anonymous class. Given that the anonymous class uses a copy of the value, should the value changes with time then for the same variable there could be two different values, which is incorrect. – Lefteris Laskaridis Nov 23 '13 at 10:53