aspose file tools*
The moose likes Beginning Java and the fly likes copying an object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "copying an object" Watch "copying an object" New topic
Author

copying an object

Niels Tielenburg
Ranch Hand

Joined: Aug 19, 2009
Posts: 44
I want to copy an object called t1. I do that like this:


What I don't understand is the output: Why, when I set the test value of t1 to another value, the value of t2 also changes to that value?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38334
    
  23
You have not copied the object. You have two references to the same object, set up with Tester t2 = t1; For copying, you should override the clone() method and implement the Cloneable interface, or maybe better, give your Tester class a copy constructor.
Niels Tielenburg
Ranch Hand

Joined: Aug 19, 2009
Posts: 44
ok thanks, got it working ;)
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14103
    
  16

Maybe this confuses you because you know C++?

This happens because variables in Java do not represent the objects themselves directly (like in C++); in Java, variables are references to objects. Line 4 in your code makes variable t2 refer to the same object that variable t1 refers to. It doesn't copy the object itself.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38334
    
  23
Niels Tielenburg wrote:ok thanks, got it working ;)
Well done, and "you're welcome"
Niels Tielenburg
Ranch Hand

Joined: Aug 19, 2009
Posts: 44
oh yes, thank you for your help:P
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: copying an object