Interview Questions

How do I copy an object in Java?

Java Interview Questions for Cloning and Cloneable


(Continued from previous question...)

How do I copy an object in Java?

1.
Create a copy constructor:

class DummyBean {
private String dummy;

public DummyBean(DummyBean another) {
this.dummy = another.dummy; // you can access
}
}

Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in Effective Java.

2.
, Consider the below code:

DummyBean dum = new DummyBean();
dum.setDummy("foo");
System.out.println(dum.getDummy()); // prints 'foo'

DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'

dum.setDummy("bar");
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'

(Continued on next question...)

Other Interview Questions