Search code examples
javafinal

JPL 8:a situation,the difference between effectively final and final


Effectively final code

public void say() {

    String b = "222"; // effectively final b

    class A {

        public A(String c) {
            b = "123"; // error
        }

    }

    b = "123"; // success; if b is final, it is an error

}

Is there a more detailed difference?


Solution

  • If your variable is affected after being declared (e.g. anytime you write "b = "123") then it is not effectively final.

    In inner class or nested class (such as your class A), you can only reference variable from the outer scope (such as b) that are effectively final.

    The same restriction applies to constructs that are derived from nested classes such as lambdas.

    Declaring a variable with the "final" keyword is a convenient way to be sure that you variable is effectively final.