Referring to non-concluding fields of the surrounding class inside an anonymous inner class in Java

In Java, I know that you can do something like this:

public class Greeter {
    public void greetEventually() {
        final String greeting = "Hello!";
        Job j = new Job() {
            public void run() {
                System.out.println(greeting);
            }
        };
        j.schedule();
    }
}

At some point in the future, this will lead to anonymous Job. This works because anonymous classes are allowed to refer to final variables in the scope.

I am not sure of the following:

public class Greeter {
    private String greeting;

    // ... Other methods that might mutate greeting ...

    public void greetEventually() {
        Job j = new Job() {
            public void run() {
                System.out.println(greeting);
            }
        };
        j.schedule();
    }
}

In this case, my anonymous one Jobrefers to the non-final field of the enclosing class. When the run is completed, will I see the value of the field greeting, as it was when creating the task, or how it happens when it is completed? I think I know the answer, but I thought it was an interesting question, and first he left me and a couple of colleagues guessing themselves for a few minutes.

+3
3

greeting, Job.

final , -.

+9

() this). this final. final, () . , this, .

public class Greeter {
    private String greeting;

    // ... Other methods that might mutate greeting ...

    public void greetEventually() {

        private final Greeter greeter = this; // <---

        Job j = new Job() {
            public void run() {
                System.out.println(   greeter.greeting   ); // <---
            }
        };
        j.schedule();
    }
}
+1

, : String;

If you need only one instance of a variable (for example, for constants or shared resources), use: String personal greeting;

-1
source

Source: https://habr.com/ru/post/1732452/


All Articles