how do i create a copy of an object in java, instead of a pointer
Most objects have a method clone() that will return a copy of that object, so in your case
f2 = f1.clone()
First, have your class implement the Cloneable
interface. Without this, calling clone()
on your object will throw an exception.
Next, override Object.clone()
so it returns your specific type of object. The implementation can simply be:
@Override
public MyObject clone() {
return (MyObject)super.clone();
}
unless you need something more intricate done. Make sure you call super.clone()
, though.
This will call all the way up the hierarchy to Object.clone()
, which copies each piece of data in your object to the new one that it constructs. References are copied, not cloned, so if you want a deep copy (clones of objects referenced by your object), you'll need to do some extra work in your overridden clone()
function.
You use clone.
Use something like
f2 = f1.clone();
If you have custom properties (or members), you should override clone in your class to make deep copy. You can learn about shallow and deep copy here
http://javapapers.com/core-java/java-clone-shallow-copy-and-deep-copy/