Question

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");
        }
    });
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top