My question is quite simple, really:
Suppose we have a class A, whom its only field is a reference to object from class B:
private B b;.
Lets assume that only an object from A points to the reference of b.
Now suppose we serialized the A object.
So now, apparently nothing points to object b (of type B). Will garbage-collector might "kill" b? and if it does - didn't we lose information of A?
Will A still have a legit reference to b when it will be deserialized?
I would be grateful for an explanation about this confusing situation. Thanks!
Assuming your class B
implements Serializable
as well, serializing the instance of A
will also serialize its nested object b
.
The original instance referenced by b
will get garbage collected if nothing else points to it and to your original instance of A
. But if you deserialize A
, it will also deserialize the nested b
, creating a new instance of both A
and B
in the process.
If you do not wish b
to be serialized here, you need to mark the reference as transient
. Deserializing A
will then have null
assigned to b
.