Java Why do anonymous inner class parameter references need to be decorated with final?

  • 2021-07-18 07:52:03
  • OfStack

In fact, in addition to anonymous inner class parameters, external variables used inside methods and inner classes in scope must also be final Of. The reasons are roughly summarized as follows:

The simple explanation is:

Local variables in a method have a short life cycle, and the variables are destroyed after the end of the method. final is added to prolong the life cycle of variables.

Step 1 to explain:

Inner classes usually contain callbacks, When the function referencing the anonymous inner class is finished, it will be gone. Therefore, the local variable referenced in the internal class needs to be final, so that the variable can be found when calling back, and if it is a member variable of the external class, it does not need to be final, because the internal class itself will contain a peripheral reference (peripheral class.this), so 1 can be accessed when calling back.

Program example:


private Animator createAnimatorView(final View view, final int position) {
    MyAnimator animator = new MyAnimator();
    animator.addListener(new AnimatorListener() {
      @Override
      public void onAnimationEnd(Animator arg0) {
        Log.d(TAG, "position=" + position); 
      }
    });
    return animator;
  }

When accessing position in anonymous inner class callback createAnimatorView() If position is not final's, the callback cannot get its value, because the local variable is reclaimed after the function is executed. Therefore, java simply designs such a variable as final, which must not be changed once it is initialized! This ensures that any callback can get the required value.

Summarize


Related articles: