1

It's not duplicated because the other topic does not provide any suitable answer for my case. I can't use any serializers or other libraries like they advise.

class A {
Object obj;
String s;
}

What is the proper way to define a copy constructor for such class? I know how to 'deal' with String type, but what about the 'Object' class? It does not provide new Object(obj) constructor, also it does not have .clone() method.

class A {
    A(A a) {
    this.s = new String(a.s);
    this.obj = //???
}
tam
  • 23
  • 3
  • 1
    `this.s = new String(a.s);` You don't need to copy the string since strings are immutable. – tkausl Jun 25 '17 at 18:58
  • Unless `obj` is `Clonable`, there is no reliable way to copy it. The best you can do in general is to simply use `this.obj = a.obj`, and cross your fingers and hope its state isn't corrupted by one or other of the `A`s that now have a reference to it. – Andy Turner Jun 25 '17 at 18:59
  • @tkausl Yes but in this case if I do 'new String(a.s)' , when the other 'A' object is deleted the reference of this.s won't be null, will it? – tam Jun 25 '17 at 19:01
  • @AndyTurner so this Object obj must have a reference to a type that implements Clonable? – tam Jun 25 '17 at 19:02
  • Yes as far as I know `Clonable` is the only thing in Java that's similar to a copy constructor. However, Java is not C++ and doesn't exactly use copy constructors, so I'm sensing an XY problem here. Can you explain exactly what it is you are trying to accomplish? – markspace Jun 25 '17 at 19:16
  • @tam why should it become `null` in `this.s` when __the other__ object gets deleted? It won't become null either way. – tkausl Jun 25 '17 at 19:50
  • When an object becomes unreferenced its references go with it, but not the objects to which they point. "Deleting" a pointer doesn't do anything to the object itself. The object itself can only be collected after there are no more pointer chains from the active code that can reach it. – Lew Bloch Jun 25 '17 at 20:07

0 Answers0