How do I copy an object in Java?

Total Post:47

 1136  View(s)
Rate this:
DummyBean dum = new DummyBean();
System.out.println(dum.getDummy()); // prints 'foo'
DummyBean dumtwo = dum;
System.out.println(dumtwo.getDummy()); // prints 'foo'
System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo'
So, I want to copy the 'dum' to dumtwo' and I want to change 'dum' without affecting the 'dumtwo'. But the above code is not doing that. When I change something in 'dum', the same change is happening in 'dumtwo' also.

I guess, when I say dumtwo = dum, Java copies the reference only. So, is there any way to create a fresh copy of 'dum' and assign it to 'dumtwo' ?
  1. Post:397

    Re: How do I copy an object in Java?

    public class Deletable implements Cloneable{
        private String str;
        public Deletable(){
        public void setStr(String str){
            this.str = str;
        public void display(){
            System.out.println("The String is "+str);
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
    and wherever you want to get another object, simple perform cloning. e.g:

    Deletable del = new Deletable();
    Deletable delTemp = (Deletable ) del.clone(); // this line will return you an independent
                                     // object, the changes made to this object will
                                     // not be reflected to other object

    In your case object is copied as a shallow copy, but if you need independent object you need to clone this object as deep copy.