문제

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