Why a non-final “local” variable cannot be used inside an inner class, and instead a non-final field of the enclosing class can?

前端 未结 4 1794
囚心锁ツ
囚心锁ツ 2020-11-30 20:36

There are some topics on Stack Overflow on the compiler error Cannot refer to a non-final variable message inside an inner class defined in a different method a

4条回答
  •  悲&欢浪女
    2020-11-30 21:12

    The value you use must be final, but the non-final fields of a final reference can be changed. Note: this is implicitly a final reference. You cannot change it.

    private String enclosingClassField;
    private void updateStatus() {
        final MutableClass ms = new MutableClass(1, 2);
        Runnable doUpdateStatus = new Runnable() {
             public void run() {
                 // you can use `EnclosingClass.this` because its is always final
                 EnclosingClass.this.enclosingClassField = "";
                 // shorthand for the previous line.
                 enclosingClassField = "";
                 // you cannot change `ms`, but you can change its mutable fields.
                 ms.x = 3;
             }
        }
        /* do something with doUpdateStatus, like SwingUtilities.invokeLater() */
    }
    

提交回复
热议问题