Creating a copy of an object without coping it's property references


To explain:

public class SomeClass { int aNumber = 0; public void changeNumber(int number){ aNumber = number; } public int getNumber(){ return aNumber; } } public class Testapp { public static void main(String[] args) { NewClass object1 = new NewClass(); NewClass object2 = object1; object1.changeNumber(5); object2.changeNumber(2); System.out.println("object1: "+object1.getNumber()); System.out.println("object2: "+object2.getNumber()); } }

This will output: object1: 2 object2: 2

How would I make it output: object1: 5 object2: 2


You have two options:

1) Implement a copy constructor:

public SomeClass(SomeClass c) { this.aNumber = c.aNumber; }

And then to create a copy:

SomeClass object2 = new SomeClass(object1);

2) Implement the Cloneable interface and override Object.clone():

public class SomeClass implements Cloneable { public SomeClass clone() { super.clone(); } }

Then to create a copy:

SomeClass object2 = object1.clone();

<strong>Note:</strong> I have omitted any code that does not change.


You are not doing a copy of the object, you are copying the reference. That means that both variables refer to the same object.

To create an object, you must use new or call a method that uses it.

Since you want a copy, you should make your object implement Cloneable (and, if needed, implement clone()).


How you have it set up right now is that both object1 and object2 are pointing at the same spot in memory. You will have to do this:

NewClass object1 = new NewClass(); NewClass object2 = new NewClass(); object1.changeNumber(5); object2.changeNumber(2); System.out.println("object1: "+object1.getNumber()); System.out.println("object2: "+object2.getNumber());

This way, object1 and object2 are completely separate Objects.


public class Testapp { public static void main(String[] args) { NewClass object1 = new NewClass(); NewClass object2 = new NewClass(); object1.changeNumber(5); object2.changeNumber(2); System.out.println("object1: "+object1.getNumber()); System.out.println("object2: "+object2.getNumber()); } }

You should call a new instantiation of the object otherwise they refer to the same position in memory.


<strong>1.</strong> You have <strong>copied the reference Not the object.</strong>

<strong>2.</strong> As both the <strong>Object Reference Variables are pointing to the Same object on the heap, you are getting 2 as the answer for both of them..</strong>

<strong>3.</strong> Use new <strong>operator to create and assign another object to the object2 reference.</strong>

<strong>One more thing... its not NewClass, but SomeClass as its mentioned in your code</strong>

SomeClass object1 = new SomeClass(); SomeClass object2 = new SomeClass(); object1.changeNumber(5); object2.changeNumber(2); System.out.println("object1: "+object1.getNumber()); System.out.println("object2: "+object2.getNumber());


Object is an instance of class and capable of holding state. Object is created using new operator - in your case object is created at new NewClass()

NewClass object1 and NewClass object2 are object reference variable - these are like pointers in C/C++. Reference variable do not hold state - they just point to memory location where object state is located.

When you say NewClass object1 = new NewClass() - the new operator creates instance of NewClass and returns the memory location that gets stored in object1 reference variable. When you say NewClass object2 = object1 - the memory location details held in object1 are copied to object2 - important thing to note over here is that no new object is created. There is only one object and hence only one state - that is why when you change state using object1 or object2 reference variable the previous value is overwritten.

If you want two objects then you need to invoke new twice - that will allocate separate memory location for each object. In case you have an object and want similar copy of the object - copying its state to new memory location - then you need to use the clone() method of Object class. Cloning creates a new object and copies the current state of object to new object - so if you call NewClass object2 = object1.clone() that would create new object and copy state of object1 to that, returning the reference to object2 - here object2 is also called as local copy. You need to follow java specifications for cloning - that is you need to implement Cloneable interface to support cloning of objects - please refer this link to start with <a href="http://en.wikipedia.org/wiki/Clone_(Java_method" rel="nofollow">http://en.wikipedia.org/wiki/Clone_(Java_method</a>)


  • Suspending event listeners
  • AngularJS : transclude ng-repeat inside directive
  • How to protect the mp3 file from read or copy on Android?
  • Enable Bootstrap Intellisense using Angular 4 in WebStorm
  • Buffer a large file; BufferedInputStream limited to 2gb; Arrays limited to 2^31 bytes
  • Simplify where clause with repeated associated type restrictions
  • How to open html table in xls on click of a button
  • using System.Speech.Synthesis with Windows10 universal app (XAML-C#)
  • GAE: Way to get reference to an HttpSession from its ID?
  • Spring boot 2.0.0.M4 required a bean named 'entityManagerFactory' that could not be found
  • What is the purpose of TaskExecutor in spring?
  • When to use `image` and when to use `Matrix` in Emgu CV?
  • Update CALayer sublayers immediately
  • JFileChooser in front of fullscreen Swing application
  • Incrementing object id automatically JS constructor (static method and variable)
  • Does CUDA 5 support STL or THRUST inside the device code?
  • How to extract text from Word files using C#?
  • When should I choose bucket sort over other sorting algorithms?
  • Hazelcast - OperationTimeoutException
  • To display the title for the current loaction in map in iphone
  • How do you troubleshoot character encoding problems?
  • Akka Routing: Reply's send to router ends up as dead letters
  • Calling of Constructors in a Java
  • AT Commands to Send SMS not working in Windows 8.1
  • Traverse Array and Display in markup
  • Transpose CSV data with awk (pivot transformation)
  • Rails 2: use form_for to build a form covering multiple objects of the same class
  • Acquiring multiple attributes from .xml file in c#
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?
  • Understanding cpu registers
  • How do I configure my settings file to work with unit tests?
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • How can I remove ASP.NET Designer.cs files?
  • Are Kotlin's Float, Int etc optimised to built-in types in the JVM? [duplicate]
  • Is it possible to post an object from jquery to bottle.py?
  • unknown Exception android
  • Does armcc optimizes non-volatile variables with -O0?
  • failed to connect to specific WiFi in android programmatically
  • Conditional In-Line CSS for IE and Others?
  • java string with new operator and a literal