After calling the code B ref = (new A()).getB() Java heap will contain the variable ref , which points to the same anonymous object as (new A()).b , which, in turn, has an internal reference to your new A() . There are no other references to the new A() object.
Your question: how can we force the garbage collection of object A to save an object of anonymous b? Answer: you cannot, because if you could, what would happen to the code in b that uses the internal reference to A?
If you know that the code of your class B does not refer to its enclosing class, you can declare it static, that is, it will not receive an internal reference to its enclusing class. To do this, you need to make it a nested class, since you cannot eliminate anonymous classes as static:
public class A { static class Bimpl implements B { public void method() { do something } }; private B b = new Bimpl(); public B getB() { return b; } } public interface B { void method(); }
If your code calls B ref = (new A()).getB() , in this situation the new A() object will be available for garbage collection, since there is no link to it.
source share