This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

copying an object

 
Niels Tielenburg
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 48396
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok thanks, got it working ;)
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15207
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Posts: 48396
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Niels Tielenburg wrote:ok thanks, got it working ;)
Well done, and "you're welcome"
 
Niels Tielenburg
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
oh yes, thank you for your help:P
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic