1

I want to copy an object in java without copying reference.

Object o1 = new Object();
Object o2 = o1;

But o2 should not copy reference of o1. So any changes done in o2 must not affect o1.

How do we do this in java ?

Setu
  • 149
  • 1
  • 10
  • clone() method is specific to Object class. If I have to copy object of some specific class, I think clone won't work. – Setu Sep 25 '14 at 07:00
  • 1
    @Setu, as pointed out by others below, you need to override the `clone` method for specific classes. – Eric Sep 25 '14 at 07:06

3 Answers3

3

You can override clone() method which will create a copy of entire object graph (deep copy) and create a new object.

Note: Every class will inherit default clone() implementation from Object class. But you must override the method to perform copy depending on the contents of your object.

Just FYI:

The default Object.clone() is a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable.

And when you implement Cloneable, you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.

Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
1

You can use Object.clone() method to clone the object:

Object o2 = o1.clone();
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

If you need copy other classes than Object, make a copy constructor or static factory method. Effect is something like this:

MyClass o1 = new MyClass();
MyClass o2 = new MyClass(o1); // in constructor make new object with data from o1 attributes

or

MyClass o1 = new MyClass();
MyClass o2 = MyClass.makeCopy(o1); // make static method for create new copy (similar like above)

Don't use clone. -> Effective Java

MWL
  • 9
  • 2