---
title: "How do I copy an object in Java?"  
description: "How do I copy an object in Java?"  
author: "Anonymous User"  
published: 2015-07-24  
updated: 2015-07-25  
canonical: https://www.mindstick.com/forum/23375/how-do-i-copy-an-object-in-java  
category: "java"  
tags: ["java"]  
reading_time: 2 minutes  

---

# How do I copy an object in Java?

```
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'
```

So, I want to [copy](https://www.mindstick.com/forum/161993/explain-the-numpy-array-copy-vs-view-with-example) the 'dum' to dumtwo' and I want to change 'dum' without affecting the 'dumtwo'. But the above [code](https://yourviews.mindstick.com/view/85458/alan-turing-the-mastermind-behind-cracking-the-enigma-code-during-world-war-ii) is not doing that. When I change something in 'dum', the same change is happening in 'dumtwo' also.\
I guess, when I [say](https://answers.mindstick.com/qa/116645/a1-wreckers-reviews-what-do-customers-say) dumtwo = dum, [Java](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming) copies the [reference](https://www.mindstick.com/forum/774/reference-what-does-this-error-mean-in-php) only. So, is there any way to create a [fresh](https://www.mindstick.com/articles/13161/10-fresh-marketing-strategies-for-small-business-that-really-work) copy of 'dum' and assign it to 'dumtwo' ?

## Replies

### Reply by Anonymous User

```
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.***


---

Original Source: https://www.mindstick.com/forum/23375/how-do-i-copy-an-object-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
