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.
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.
@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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.