-3

I wanted to have a function that returns a copy of the object it receives, to use it somewhere else. This is what I wrote:

public static PObject Instantiate(PObject obj)
{
    PObject other = obj;
    objects.add(other);
    return other;
}

But when I print obj + " " + other, it outputs:

PObjects.Wall@5315b42e
PObjects.Wall@5315b42e

How can I return the same object stored in a different variable?

  • 3
    You could create a copy constructor and then do `PObject other = new PObject(obj);`. – Kayaman Jun 22 '22 at 19:18
  • 1
    That'd be explicitly *not* the same object; searching for "copy Java object" will get you most of the way there. `equals` (and `hash`) exist to allow code to determine if object instances are `equal` based on whatever criteria you choose. – Dave Newton Jun 22 '22 at 19:18
  • 3
    Does this answer your question? [How do you make a deep copy of an object?](https://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object) – ATP Jun 22 '22 at 19:23

1 Answers1

0

You might need to implement Cloneable interface if you want just shallow copy so do it like this:

class PObject implements Cloneable 
{
....
 @Override
    protected Object clone()
        throws CloneNotSupportedException
    {
        return super.clone();
    }
}

And then use it like this:

public static PObject Instantiate(PObject obj)
{
    PObject other = (PObject)obj.clone();
    objects.add(other);
    return other;
}

I hope this could be a benefit.