0

let's say we have the following classes:

public class Foo {

    private final List<String> myFooList;

    public Foo(BarHelper barHelper) {
        myFooList = barHelper.getMyList();
    }

    public static void main(String[] args) {
        FooListRepository fooListRepository = new FooListRepository();
        Foo myFoo = new Foo(new BarHelper() {
            @Override
            public List<String> getMyList() {
                return fooListRepository.getList();
            }
        });

        System.out.println(myFoo.getMyFooList().toString());
    }

    public List<String> getMyFooList() {
        return myFooList;
    }

}

interface BarHelper {
    List<String> getMyList();
}

public class FooListRepository {

    private List<String> myBarList;

    public FooListRepository() {
        //initilize myBarList
    }

    public List<String> getList() {
        return myBarList;
    }
}

How would really internally the anonymous class in the main method work?

As with java documentation there would be a new class compiled, but the question is how would myTestList be handled? Would java somehow save it in the anonymous class as an internal variable?

What really hapens in backround in this line System.out.println(myFoo.getMyFooList().toString());

Does Java call FooListRepository in backround somehow ?

Thanks in advance.

  • It's part of the Oracle tutorials for anonymous classes. https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html#accessing – Michael Mar 10 '21 at 11:08
  • See this answer of the linked dupe: https://stackoverflow.com/a/53203670/1898563 – Michael Mar 10 '21 at 11:10
  • Hi @Michael thanks for your suggestions, but I couldn't find any answer in the link you send me (stackoverflow.com/a/53203670/1898563), the question is a bit specific about final variables and goes not generally how anonymous classes handle local variables. Perhaps I read something wrong ? – Ilias Mertzanidis Mar 10 '21 at 11:56

0 Answers0