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");
        }
    });
有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top