What is the lifetime of unassigned object created in a constructor in java?

Vamshi :

I have a class(A) with constructor defined as shown below. In the constructor, I have created an object for B by passing a listener(interface) implementation to it as shown below.

public class A {

    private String str;

    public A() {

       new B(new OnStringUpdatedListener() {

           public void onStringUpdated(String str) {
               A.this.str = str;
           }

       });
    }
}

In the above code object of B is not assigned to any field of A or a variable in constructor.

What is the lifetime of the object of B? Is it marked for garbage collection as soon as constructor execution completed or is it still alive since it registered a listener which modifies A's field.

Andrew Tobilko :

@Thomas' comment is nice.

It doesn't matter what OnStringUpdatedListener modifies. After constructor has been executed, B won't be accessible through any references. It will become eligible for the GC and may be garbage-collected.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92557&siteId=1