-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
  • 3
    You could create a copy constructor and then do PObject other = new PObject(obj);. Commented Jun 22, 2022 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. Commented Jun 22, 2022 at 19:18
  • 3
    Does this answer your question? How do you make a deep copy of an object? Commented Jun 22, 2022 at 19:23

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.