You need to make a method called clone and override it for the typical clone() method that comes with the Object class using @Override. After this, make a new object, and copy the data from the old object into it. Where I put /... means that more code can be added or you can take away the code I originally put.
/**
* Explanation for http://stackoverflow.com/questions/35120424/how-to-deep-copy-an-object-of-type-object
*
* @author Riley C
* @version 1/31/16
*/
public class ObjectToReturn
{
//variables
int x;
int y;
// ...
//constructor
public ObjectToReturn()
{
x = 0;
y = 0;
// ...
}
//overrides
@Override
public ObjectToReturn clone()
{
ObjectToReturn returnMe = new ObjectToReturn();
returnMe.setX(this.x);
returnMe.setY(this.y);
// ...
return returnMe;
}
//methods
public void setX(int x) {this.x = x;}
public void setY(int y) {this.y = y;}
// ...
public int getX() {return x;}
public int getY() {return y;}
// ...
}
Why you shouldn't use the default clone
From what I can remember, while clone() can sometimes generate a deep copy of an Object, it doesn't always do it.
Habits to get into
Good habits my college instructor said his company liked to see if making sure you make deep copies of arrays and objects, as well as overriding the equals, clone, and toString method which typically come with the class Object. This will allow you to use these methods on your objects with how you would like them to work, instead of the default values which may give answers that make no sense. It also is often cleaner, and is prone to throw less errors.